Jersey HelloWorld!
开发环境
Maven版本: 3.5.0
JerSey版本:2.26
Java 版本:1.8.0_131
pom.xml
[xml]
<!– https://mvnrepository.com/artifact/org.glassfish.jersey.containers/jersey-container-servlet –>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.26</version>
</dependency>
<!– https://mvnrepository.com/artifact/org.glassfish.jersey.inject/jersey-hk2 –>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>2.26</version>
</dependency>
<!– https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api –>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
[/xml]
web.xml
[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" id="WebApp_ID" version="3.0">
<display-name>DemoJersey</display-name>
<servlet>
<servlet-name>com.test.rest.App</servlet-name>
</servlet>
<servlet-mapping>
<servlet-name>com.test.rest.App</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
</web-app>
[/xml]
代码
App.java
[java]
package com.test.rest;
import javax.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;
public class App extends Application {
@Override
public Set<Class<?>> getClasses() {
HashSet<Class<?>> classes = new HashSet<Class<?>>();
classes.add(DogResource.class);
classes.add(CatResource.class);
classes.add(HelloWorldResource.class);
return classes;
}
}
[/java]
HelloWorldResource.java
[java]
package com.test.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@Path("hello")
public class HelloWorldResource {
@GET
@Produces("text/plain")
public String getHello() {
return "Hello World!";
}
}
[/java]
测试
访问:http://localhost:8080/DemoJersey/api/hello
问题
1.Exception
HTTP Status 500 - Servlet.init() for servlet Jersey REST Service threw exception type Exception report message Servlet.init() for servlet Jersey REST Service threw exception description The server encountered an internal error that prevented it from fulfilling this request. exception javax.servlet.ServletException: Servlet.init() for servlet Jersey REST Service threw exception
解决办法
增加依赖
[xml]
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
</dependency>
[/xml]
参考:https://stackoverflow.com/questions/44088493/jersey-stopped-working-with-injectionmanagerfactory-not-found