首页 > 解决方案 > 请求 http://localhost:4080/testAPI/rest/hello 后未找到 HTTP 状态 404

问题描述

下面是我的 web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>testAPI</display-name>
  
<servlet>
 <servlet-name>testAPI</servlet-name>
 <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
 <init-param>
  <param-name>jersey.config.server.provider.packages</param-name>
  <param-value>test</param-value>
 </init-param>
 <load-on-startup>1</load-on-startup>
</servlet>
 <servlet-mapping>
   <servlet-name>testAPI</servlet-name>
   <url-pattern>/rest/*</url-pattern>
 </servlet-mapping>
</web-app>

我的类文件如下所示:

package testAPI;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;


@Path("/hello")
public class Hello {
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String sayHello()
    {
        String resource="<? xml version='1.0' ?>" + "<hello> hello from XML</hello>";
        return resource;
    }
    /*@GET
    @Produces(MediaType.APPLICATION_JSON)
    public String sayHelloJSON()
    {
        String resource=null;
        return resource;
    }*/

}

我的 java 版本是 8,tomcat 7 和 jersey 2.25。我创建了一个动态网络项目。当我访问 http://localhost:4080/ - tomcat 主页打开。http://localhost:4080/testAPI/ 将显示 index.html。但是,当我尝试访问 http://localhost:4080/testAPI/rest/hello- 我得到 http 状态 404 not found

标签: javaspringservlets

解决方案


您在 web.xml 中的参数值需要指向包含您的类的包。

<init-param>
  <param-name>jersey.config.server.provider.packages</param-name>
  <param-value>test</param-value>
 </init-param>

应该

<init-param>
  <param-name>jersey.config.server.provider.packages</param-name>
  <param-value>testAPI</param-value>
</init-param>

推荐阅读