泽西岛你好世界给了404

cyb*_*mon 6 java tomcat jersey

我的java类中有以下代码

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;

@Path("/hello")
public class Hello {
    //This method is called is TEXT_PLAIN is request
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String sayPlainTextHello(){
        return "Hello World";
    }

    //this method is called if TEXT_XML is requested
    @GET
    @Produces(MediaType.TEXT_XML)
    public String sayXMLHello(){
        return "<?xml version=\"1.0\"?>"+"<Hello> Hello World"+"</hello>";
    }

    //this method is called if HTML is requested
    @GET
    @Produces(MediaType.TEXT_HTML)
    public String sayHtmlHello(){
        return "<html>"+"<title>"+"hello jersey"+"</title>"+"<body><h1>"+"hello World!!"+"</body></h1>"+"</html>";
    }
}
Run Code Online (Sandbox Code Playgroud)

当我输入时,我编译并将其导出为.WAR文件

http://127.0.0.1/test_server/hello

我得到了404.我在WTP中试过它,cURL它们都返回404 ..我正在使用tomcat 7.0.26

注意:我在端口80上运行Tomcat,其他servlet按预期响应.

web.xml配置

<display-name>Jersey_Test</display-name>
  <servlet>
    <servlet-name>Hello</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.example.service</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>Hello</servlet-name>
    <url-pattern>/*</url-pattern>
Run Code Online (Sandbox Code Playgroud)

以下URL为我提供了Http状态500

 http://localhost/Jersey_Test/rest/hello
java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer 
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 9

如果您还没有在您的注册中注册JAX-RS servlet实现,那么就会发生这种情况web.xml.Jersey需要以下配置:

<servlet>
    <servlet-name>jersey</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.example.service</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>jersey</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>  
Run Code Online (Sandbox Code Playgroud)

com.sun.jersey.config.property.packages初始化参数值必须指向你所有的服务包.但是,您的代码段缺少package声明.我不确定是否为了简洁而省略了这一点,但无包装类对于本身位于包中的类是不可见的(例如Tomcat和Jersey引擎本身).上面的web.xml例子假设你有一个

package com.example.service;
Run Code Online (Sandbox Code Playgroud)

在您的Web服务类上.相应地修复或更改它.

请注意,URL模式/*因此意味着所有请求将通过Jersey传递.如果您需要在同一个Web应用程序中部署其他servlet,JSP或静态内容,则可能需要指定更具体的URL模式.例如

<url-pattern>/rest/*</url-pattern>
Run Code Online (Sandbox Code Playgroud)

您只需将请求URL更改为http:// localhost/test_server/rest/hello.


cyb*_*mon 1

问题已经解决了,我就是这样做的。

我从构建路径中删除了球衣 .jar 文件并将它们替换到WEB-INF\lib文件夹中,一切正常。