mvn archetype:generate \
-DarchetypeGroupId=org.glassfish.jersey.archetypes \
-DarchetypeArtifactId=jersey-quickstart-grizzly2 \
-DarchetypeVersion=2.27
cd project-root
mvn clean package exec:java
輸出確認:
Jun 19, 2017 11:12:23 PM org.glassfish.grizzly.http.server.NetworkListener start
INFO: Started listener bound to [localhost:8080]
Jersey app started with WADL available at https://localhost:8080/myapp/application.wadl
GET https://localhost:8080/myapp/application.wadlGET https://localhost:8080/myapp/myresource → 返回 Got it!// 啟動類 Main.java
public class Main {
public static final String BASE_URI = "https://localhost:8080/myapp/";
public static HttpServer startServer() {
ResourceConfig rc = new ResourceConfig().packages("org.drsoft.rest");
return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
}
public static void main(String[] args) throws IOException {
HttpServer server = startServer();
System.in.read(); // 阻塞等待回車停止
server.shutdownNow();
}
}
// 資源類 MyResource.java
@Path("myresource")
public class MyResource {
@GET @Produces(MediaType.TEXT_PLAIN)
public String getIt() { return "Got it!"; }
}
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<configuration>
<mainClass>org.drsoft.rest.Main</mainClass>
</configuration>
</plugin>
mvn archetype:generate \
-DarchetypeGroupId=org.glassfish.jersey.archetypes \
-DarchetypeArtifactId=jersey-quickstart-webapp
<web-app version="3.1" xmlns="https://xmlns.jcp.org/xml/ns/javaee">
<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>org.drsoft.rest</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/webapi/*</url-pattern>
</servlet-mapping>
</web-app>
Run → Edit Configurations → + → Tomcat Server → LocalApplication context 為 /RESTWebAPPArtifact: 项目名:war explodedGET https://localhost:8080/RESTWebAPP/webapi/myresource → Got it!
public class MyResourceTest {
private HttpServer server;
private WebTarget target;
@Before
public void setUp() {
server = Main.startServer();
Client client = ClientBuilder.newClient();
target = client.target(Main.BASE_URI);
}
@After
public void tearDown() { server.stop(); }
@Test
public void testGetIt() {
String resp = target.path("myresource").request().get(String.class);
assertEquals("Got it!", resp);
}
}
jersey-container-servlet 而非 jersey-serverjersey-media-json-jackson 並註冊 JacksonFeature