本节讲解如何快速使用jersey构建Restful Webservice,使用的是轻量级的Grizzly服务器发布服务。
一般情况下我们使用maven时,依赖的jar都使用稳定版,不会使用snapshot版,但如果你想使用jersey的snapshot版的话,请引入以下配置到pom文件中:
snapshot-repository.java.net
Java.net Snapshot Repository for Maven
https://maven.java.net/content/repositories/snapshots/
default
开始搭建项目
1、使用以下命令创建一个基于Grizzly的jersey项目(也可以在Eclipse中安装jersey插件生成):
mvn archetype:generate -DarchetypeArtifactId=jersey-quickstart-grizzly2
-DarchetypeGroupId=org.glassfish.jersey.archetypes -DinteractiveMode=false
-DgroupId=com.example -DartifactId=simple-service -Dpackage=com.example
-DarchetypeVersion=2.25.
命令中的-DgroupId/-DartifactId/-Dpackage可以随意改动,也可以等到生成项目后再改pom文件。其他参数请勿改动。
2. 浏览生成的项目
通过步骤一后生成的项目会在com.example下包含Main、MyResource、以及MyResourceTest三个类。
Main: 用来配置启动Grizzly 服务器并部署Resource。
MyResource: 定义基于JAX-RS的Restfull接口。代码如下:
package com.example;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/**
* Root resource (exposed at "myresource" path)
*/
@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!";
}
}
MyResourceTest: 启动服务,调用restfull接口并判断返回值。
package com.example;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import org.glassfish.grizzly.http.server.HttpServer;
public class MyResourceTest {
private HttpServer server;
private WebTarget target;
@Before
public void setUp() throws Exception {
server = Main.startServer();
Client c = ClientBuilder.newClient();
target = c.target(Main.BASE_URI);
}
@After
public void tearDown() throws Exception {
server.stop();
}
/**
* Test to see that the message "Got it!" is sent in the response.
*/
@Test
public void testGetIt() {
String responseMsg = target.path("myresource").request().get(String.class);
assertEquals("Got it!", responseMsg);
}
}
3.可以使用mvn clean test/run as -Junit Test运行MyResourceTest 测试程序
4.使用mvnexec:java/run as -Java Application运行Main程序