【问题标题】:JAX-RS, GlassFish, Eclipse. A simple web service doesn't workJAX-RS、GlassFish、Eclipse。一个简单的 Web 服务不起作用
【发布时间】:2014-05-07 03:22:16
【问题描述】:

我正在尝试在我的机器上运行一个简单的“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 "<greeting>Hello REST</greeting>";
    }

    /**
     * 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/hello,其中hello-rest 是 Eclipse 项目的名称和 GlassFish 管理页面建议的根路径。

【问题讨论】:

  • 请将您的web.xml 添加到问题中。

标签: java eclipse rest glassfish


【解决方案1】:

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

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

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("your-base-url")
public class ApplicationConfig extends Application {

}

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

【讨论】:

    【解决方案2】:
    @GET
    @Produces("application/xml")
    @path("/getxml")
    public String getXml() {
        // TODO return proper representation object
        return "<greeting>Hello REST</greeting>";
    }
    
    Your url should be http://localhost:8080/hello-rest/hello/getxml
    

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

    • 您可以使用 SOAPUI 来测试服务。请确保您选择了正确的方法。

    • 方法为 'GET'

    • 端点为“主机名:8080”

    • 资源为“hello-rest/hello/getxml”

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      相关资源
      最近更新 更多