所以我尝试使用Jersey 2.25创建一个REST服务,它将在Tomcat 9上运行。我使用gradle作为构建工具。基本上,我关注this vogella tutorial,我做了那里提到的一切。但是,当我尝试通过访问http://localhost:8080/com.krozona.jersey.first/rest/hello在tomcat9上运行它时,我收到404错误。
这是我的web.xml: -
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>com.krozona.jersey.first</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<!-- Register resources and providers under com.vogella.jersey.first package. -->
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.krozona.jersey.first</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
我的资源类: -
package com.krozona.jersey.first;
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 {
// This method is called if TEXT_PLAIN is request
@GET
@Produces(MediaType.TEXT_PLAIN)
public String sayPlainTextHello() {
return "Hello Jersey";
}
// This method is called if XML is request
@GET
@Produces(MediaType.TEXT_XML)
public String sayXMLHello() {
return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
}
// This method is called if HTML is request
@GET
@Produces(MediaType.TEXT_HTML)
public String sayHtmlHello() {
return "<html> " + "<title>" + "Hello Jersey" + "</title>"
+ "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";
}
}
最后,我的build.gradle: -
/*
* This file was generated by the Gradle 'init' task.
*
* This generated file contains a sample Java Library project to get you started.
* For more details take a look at the Java Libraries chapter in the Gradle
* user guide available at https://docs.gradle.org/4.5.1/userguide/java_library_plugin.html
*/
plugins {
// Apply the java-library plugin to add support for Java Library
id 'java-library'
}
dependencies {
api 'org.apache.commons:commons-math3:3.6.1'
implementation 'com.google.guava:guava:23.0'
testImplementation 'junit:junit:4.12'
compile 'org.glassfish.jersey.containers:jersey-container-servlet:2.25.1'
}
repositories {
jcenter()
}
apply plugin: 'war'
apply plugin: 'eclipse-wtp'
project.webAppDirName = 'WebContent'
任何帮助都将非常感激。谢谢!
答案 0 :(得分:0)
与在Tutorial中提到的一样:
此URL源自项目中的上下文根值 属性Web项目设置(默认情况下,这是您的应用程序 名称),并添加了servlet映射URL模式和hello 来自类文件的@Path注释。
因此请确保使用正确的URL:
http://localhost:8080/{your application's name}/rest/hello
端口号也必须正确。