JAX-RS,GlassFish,Eclipse。 简单的Web服务不起作用

我试图在我的机器上运行一个简单的“Hello World”RESTful Web服务。 我使用Eclipse Kepler和GlassFish 4.0。 我能够部署该服务,我在GlassFish的管理页面上看到它,但当我尝试访问它时,我收到以下错误:“HTTP状态404 – 未找到”。

这里是简单服务的代码:

import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; @Path("hello") public class HelloRest { @SuppressWarnings("unused") @Context private UriInfo context; /** * Default constructor. */ public HelloRest() { // TODO Auto-generated constructor stub } /** * Retrieves representation of an instance of HelloRest * @return an instance of String */ @GET @Produces("application/xml") public String getXml() { // TODO return proper representation object return "Hello REST"; } /** * PUT method for updating or creating an instance of HelloRest * @param content representation for the resource * @return an HTTP response with content of the updated or created resource. */ @PUT @Consumes("application/xml") public void putXml(String content) { } } 

为了访问该服务,我尝试以下URL: http://127.0.0.1:8080/hello-rest/hellohttp://127.0.0.1:8080/hello-rest/hellohttp://127.0.0.1:8080/hello-rest/hello / hello-rest http://127.0.0.1:8080/hello-rest/hello / hello-rest ,其中hello-rest是Eclipse项目的名称和管理页面建议的根路径GlassFish的。

您的代码似乎没问题,因此最有可能的问题是您没有为您的服务定义基本url。 你需要告诉JAX-RS(Jersey是GlassFish中的实现),它必须截取哪个url模式作为你的端点(base url)。

实现此目的的一种方法是使用可以添加到项目中任何包的应用程序类(您也可以在web.xml文件中定义必要的内容,我将不会介绍)。 以下是代码:

 import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; @ApplicationPath("your-base-url") public class ApplicationConfig extends Application { } 

您可以使用@ApplicationPath批注来定义基本URL。 然后,您可以访问http://127.0.0.1:8080/hello-rest/your-base-url/hello访问您的服务

 @GET @Produces("application/xml") @path("/getxml") public String getXml() { // TODO return proper representation object return "Hello REST"; } Your url should be http://localhost:8080/hello-rest/hello/getxml 

您应该在方法级别提及路径,因此请求将重定向到适当的方法。

  • 您可以使用SOAPUI来测试服务。 请确保您选择了正确的方法。
  • ‘GET’的方法
  • 终点为’主机名:8080′
  • 资源为’hello-rest / hello / getxml’

    如果你遇到同样的问题。 请在tomcat控制台中附加更多日志/exception。