[英]404 Error using Jersey and Apache Tomcat for 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 將Jersey連接為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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.