如果用 Jersey maven archetype 成功创建了这个项目,那么在你当前的路径下就已经创建了一个名为simple-service
项目。它包含了一个标准的Maven项目结构:
说明
|
文件目录
|
---|---|
在项目根目录下的的项目构建和管理配置描述文件 | ?pom.xml
|
项目源代码文件 | src/main/java |
项目测试源代码 | src/test/java |
在原文路径下的com.example
包中有两个 class 文件,这个 Main 类主要是负责启动 Grizzly 容器,同时也为这个容器配置和部署 JAX-RS 应用。
在同一个包内的另外一个类 MyResource 类是 JAX-RS 的一个实现的源代码,如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
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!"
;
????
}
}
|
一个 JAX-RS 资源是一个可以处理绑定了资源的URI的HTTP请求的带有注解的POJO,详细内容可以看第三章。在我们的例子中,单一的资源暴露了一个公开的方法,能够处理HTTP GET请求,绑定在/myresource
URI路径下,可以产生媒体类型为“text/plain”的响应消息。在这个示例中,资源返回相同的“Got it!”应对所有客户端的要求。
在src/test/java
目录下的 MyResourceTest 类是对 MyResource 的单元测试,他们具有相同的包?com.example 中。但是这个单元测试类被放置到 maven 工程中的测试源代码目录下
?src/test/java(为了增加代码的简洁性,一些代码的注释和 JUnit 的导入类被省略了)。
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);
????
}
}
|
在这个单元测试中静态方法?Main.startServer()
首先将 Grizzly 容器启动,然后服务器应用部署到测试中的?setUp()
?方法。接下来,一个JAX-RS 客户端组件在相同的测试方法创建。 先是一个新的JAX-RS客户端实例生成,接着JAX-RS web target 部件指向我们部署的应用程序上下文的 root:http://localhost:8080/myapp/
(?Main.BASE_URI
?的常量值)存储在单元测试类目标区。这个区被用于实际的单元测试方法(testgetit()
)。
在 testgetit() 方法中,JAX-RS 客户端 API 是用来连接并发送 HTTP GET 请求的 MyResource JAX-RS 资源类侦听在/myresource
?的URI。同样作为 JAX-RS API 方法调用链的一部分,回应以Java字符串类型被读到。在测试方法的第二行,响应的内容(从服务器返回的字符串)跟测试断言预期短语比较。要了解更多有关使用 JAX-RS 客户端API,请参阅第5章客户端API。