HelloWorld 示例中的 JaxRS 路径

JaxRS path in HelloWorld example

这是 Restful 服务的 JEE 7 教程中的第一个示例,只需将 "hello world" 打印到屏幕上。本教程在 Glassfish 中配置为 运行,但我正在 Eclipse 和 Wildfly 中对其进行测试。当我启动应用程序 Wildfly 时,它显示“http://localhost:8080/hello/”,错误消息是:

Failed to execute: javax.ws.rs.NotFoundException: RESTEASY003210: Could not find resource for full path: http://localhost:8080/hello/

然后我 运行 这个 URL: "http://localhost:8080/hello/helloworld", it works correctly. The original tutorial has this configuration for Glassfish below, so it can directly executes "http://localhost:8080/hello" 到 运行 这个例子。

如何更改配置或源代码,以便在 Wildfly 和 Eclipse 中直接 运行“http://localhost:8080/hello”并附加 "helloworld"?原始教程甚至没有要配置的 web.xml 文件。相反,它使用 nbactions.xml 来进行配置。

<action>
            <actionName>profile</actionName>
            <goals>
                <goal>package</goal>
            </goals>
            <properties>
                <netbeans.deploy>true</netbeans.deploy>
                <netbeans.deploy.profilemode>true</netbeans.deploy.profilemode>
                <netbeans.deploy.clientUrlPart>/helloworld</netbeans.deploy.clientUrlPart>
            </properties>
        </action>

HelloWorldApplication.java

@ApplicationPath("/")
public class HelloApplication extends Application {

}

HelloWorld.java

@Path("helloworld")
public class HelloWorld {
    @Context
    private UriInfo context;

    /** Creates a new instance of HelloWorld */
    public HelloWorld() {
    }

    /**
     * Retrieves representation of an instance of helloWorld.HelloWorld
     * @return an instance of java.lang.String
     */
    @GET
    @Produces("text/html")
    public String getHtml() {
        return "<html lang=\"en\"><body><h1>Hello, World!!</h1></body></html>";
    }

    /**
     * PUT method for updating or creating an instance of HelloWorld
     * @param content representation for the resource
     */
    @PUT
    @Consumes("text/html")
    public void putHtml(String content) {
    }
}

Pom.xml

<modelVersion>4.0.0</modelVersion>
    <groupId>org.glassfish.javaeetutorial</groupId>
    <artifactId>hello</artifactId>
    <packaging>war</packaging>
    <name>hello</name>

    <parent>
      <groupId>org.glassfish.javaeetutorial</groupId>
      <artifactId>jaxrs</artifactId>
      <version>7.0.5</version>
    </parent>

应用程序路径首先由HelloWorldApplication.java class注解设置

@ApplicationPath("/")

这意味着您的应用程序将在部署的根上下文中提供服务,因此您只需转到 http://localhost:8080/hello 即可访问应用程序中的任何资源。

您在 HelloWorld.java 中定义的其余资源通过另一个 class 注释在应用程序中设置其路径:

@Path("helloworld")

因此 JAX-RS 将通过 @ApplicationPath 和资源 @Path 的组合路径使该资源可用。您可能会自己看到可以将上面的 @Path 更改为:

@Path("/")

您的资源路径将是 context-path + ApplicationPath + Path 或者,换句话说,您的场景将是 your-app-name + nothing + nothing.

当您将应用程序部署到 GlassFish 时,您甚至可以将上下文路径设置为根上下文,这样您甚至不需要在 URL 中指定 hello