【发布时间】:2019-05-10 08:34:15
【问题描述】:
我按照本教程 (https://programmerscuriosity.com/2016/09/27/simple-jersey-example-with-intellij-idea-ultimate-and-tomcat/) 使用 tomcat 在 java 中创建了一个简单的 Rest API,但我不断收到 404 错误,而且我看不出哪里出错了。
我猜错误是在我的配置中的某个地方。
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.demo</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>com.demo</groupId>
<artifactId>SimpleJersey</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
</dependency>
</dependencies>
<properties>
<jersey.version>2.23.2</jersey.version>
</properties>
</project>
MyResource.java
package demo;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/**
* Created by marom on 27/09/16.
*/
@Path("myresource")
public class MyResource {
/**
* Method handling HTTP GET requests. The returned object will be sent
* to the client as "text/plain" media type.
*
* @return String that will be returned as a text/plain response.
*/
@GET
@Produces(MediaType.TEXT_PLAIN)
public String getIt() {
return "Got it!";
}
}
我的项目结构 https://imgur.com/8b4xPP6
向 WEB-INF 添加资源 https://imgur.com/JKtmtNu
Tomcat 配置 https://imgur.com/ldJtCLf https://imgur.com/Qpxys3x
来自 localhost:8080/rest/myresource 的 404 https://imgur.com/UIPMqm1
【问题讨论】:
-
你的应用程序的上下文根是什么?
-
通过上下文根您指的是本地主机上下文吗?如果您查看 tomcat 配置图像,它应该是
http://localhost:8080/和应用程序上下文/ -
使用@Path("/myresource") 代替@Path("myresource")
-
@Path("/myresource")没有帮助@Nitika -
将
com.demo 更改为demo 因为您的 MyResource.java 驻留在 demo
标签: java rest api maven web-applications