探索新项目

========================

如果用 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. package com.example;
  2. import javax.ws.rs.GET;
  3. import javax.ws.rs.Path;
  4. import javax.ws.rs.Produces;
  5. import javax.ws.rs.core.MediaType;
  6. /**
  7. * Root resource (exposed at "myresource" path)
  8. */
  9. @Path("myresource")
  10. public class MyResource {
  11. /**
  12. * Method handling HTTP GET requests. The returned object will be sent
  13. * to the client as "text/plain" media type.
  14. *
  15. * @return String that will be returned as a text/plain response.
  16. */
  17. @GET
  18. @Produces(MediaType.TEXT_PLAIN)
  19. public String getIt() {
  20. return "Got it!";
  21. }
  22. }

一个 JAX-RS 资源是一个可以处理绑定了资源的URI的HTTP请求的带有注解的POJO,详细内容可以看第三章。在我们的例子中,单一的资源暴露了一个公开的方法,能够处理HTTP GET请求,绑定在/myresource URI路径下,可以产生媒体类型为“text/plain”的响应消息。在这个示例中,资源返回相同的“Got it!”应对所有客户端的要求。

src/test/java目录下的 MyResourceTest 类是对 MyResource 的单元测试,他们具有相同的包com.example

  1. package com.example;
  2. import javax.ws.rs.client.Client;
  3. import javax.ws.rs.client.ClientBuilder;
  4. import javax.ws.rs.client.WebTarget;
  5. import org.glassfish.grizzly.http.server.HttpServer;
  6. ...
  7. public class MyResourceTest {
  8. private HttpServer server;
  9. private WebTarget target;
  10. @Before
  11. public void setUp() throws Exception {
  12. server = Main.startServer();
  13. Client c = ClientBuilder.newClient();
  14. target = c.target(Main.BASE_URI);
  15. }
  16. @After
  17. public void tearDown() throws Exception {
  18. server.stop();
  19. }
  20. /**
  21. * Test to see that the message "Got it!" is sent in the response.
  22. */
  23. @Test
  24. public void testGetIt() {
  25. String responseMsg = target.path("myresource").request().get(String.class);
  26. assertEquals("Got it!", responseMsg);
  27. }
  28. }

在这个单元测试中(译者注:测试用到了 JUnit ),静态方法Main.startServer()首先将 Grizzly 容器启动,而后服务器应用部署到测试中的setUp() 方法。接下来,一个JAX-RS 客户端组件在相同的测试方法创建。 先是一个新的JAX-RS客户端实例生成并,接着JAX-RS web target 部件指向我们部署的应用程序上下文的根:http://localhost:8080/myapp/Main.BASE_URI 的常量值)存储在单元测试类目标区。这个区被用于实际的单元测试方法(testgetit())。

在testgetit()方法中,JAX-RS 客户端 API 是用来连接并发送 HTTP GET 请求的 MyResource JAX-RS 资源类侦听在/myresource 的URI。同样作为 JAX-RS API 方法调用链的一部分,回应以Java字符串类型被读到。在测试方法的第二行,响应的内容(从服务器返回的字符串)跟测试断言预期短语比较(译者注:即assertEquals方法)。要了解更多有关使用 JAX-RS 客户端API,请参阅第5章客户端API