404将Jersey和Apache Tomcat用于Web Api时出错



我正在尝试使用Eclipse/Java,并在Eclipse中制作一个动态Web项目。我已经在网上学习了教程,并查看了其他几篇Stackoverflow帖子,但我仍然有同样的问题。

当我运行服务器并尝试访问端点/test时,我会得到一个404错误。这是我的代码:

我的Java类:

package TestPackage;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
@Path("/test")
public class Test {
@GET
public String Hello() {
return "hello";
}
}

我的Pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>RestDemo</groupId>
<artifactId>RestDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.25</version>
</dependency>
</dependencies>
</project>

我读到,如果你使用Jersey 2.+,你就不必摆弄你的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" version="3.1">
<display-name>RestDemo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

所以当我尝试调用http://localhost:8080/RestDemo/test时,我得到了一个404错误。知道发生了什么事吗?

在Servlet 2.5环境中,您必须在Web应用程序的Web.xml部署描述符文件中显式声明Jersey容器Servlet。

根据https://jersey.java.net/documentation/latest/user-guide.html#deployment.servlet

示例4.10。连接球衣作为Servlet

<web-app>
<servlet>
<servlet-name>MyApplication</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
...
</init-param>
</servlet>
...
<servlet-mapping>
<servlet-name>MyApplication</servlet-name>
<url-pattern>/myApp/*</url-pattern>
</servlet-mapping>
...
</web-app>

最新更新