我跟随this guide建立我的hello world网络服务并陷入困境,这是我的代码:
MyResource.java:
package com.example;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@Path("myresource")
public class MyResource {
@GET
@Produces("text/plain")
public String getIt() {
return "Got it!";
}
}
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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ts</groupId>
<artifactId>mtest</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>mtest Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-jetty-http</artifactId>
<version>2.19</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-jetty-servlet</artifactId>
<version>2.19</version>
</dependency>
</dependencies>
<build>
<finalName>mtest</finalName>
<plugins>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.3.0.M1</version>
</plugin>
</plugins>
</build>
web.xml:
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<!-- Servlet declaration can be omitted in which case
it would be automatically added by Jersey -->
<servlet>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
</servlet>
<servlet-mapping>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
<url-pattern>/myresource/*</url-pattern>
</servlet-mapping>
现在我的问题是:
http://localhost:8080/
获取我的jsp的hello世界,但http://localhost:8080/myresource
返回404 Element web-app must be declared
答案 0 :(得分:2)
在web.xml中添加servlet声明,如下所示
<servlet>
<servlet-name>javax.ws.rs.core.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.example</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
应该有用。有时这条路需要这样一个条。
@Path("/myresource")
看看,如果你把
<url-pattern>/myresource/*</url-pattern>
你必须点击
http://localhost:8080/myresource/myresource
一个是您的网络配置,另一个是您的资源路径。
但是,如果您在tomcat中尝试此操作,则还需要包含artifactId,如下所示:
我希望这对你有帮助。