找不到Java RESTful Web服务,404

时间:2014-10-18 19:13:27

标签: java web-services rest

我正在使用jersey 2.0创建RESTful Web服务,这是我的web.xml文件:

<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
    <servlet-name>Rest</servlet-name>
    <servlet-class>
        com.shop.domain.ShoppingApplication
    </servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>Rest</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>

我的ShoppingApplication类:

public class ShoppingApplication extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> s = new HashSet<Class<?>>();
        s.add(CustomerResource.class);
        return s;
    }   
}

我的CustomerResource类:

@Path("/customers")
public class CustomerResource{

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getCustomer(){
        return "Hello";
    }
}

使用 localhost:8080 / customers 运行时,我找到了404找不到的页面,我应该如何修复它。

1 个答案:

答案 0 :(得分:0)

在非JEE6容器中使用JAX-RS要求您提供要在web.xml中映射的JAX-RS Servlet(如Jersey)

将您的web.xml更改为

<web-app>
    <servlet>
        <servlet-name>MyApplication</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.shop.domain.ShoppingApplication</param-value>
        </init-param>
    </servlet>
    ...
    <servlet-mapping>
        <servlet-name>MyApplication</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
    ...
</web-app>

有关文档,请参阅https://jersey.java.net/documentation/latest/deployment.html#deployment.servlet.2