探索新项目
========================
如果用 Jersey maven archetype 成功创建了这个项目,那么在你当前的路径下就已经创建了一个名为simple-service项目。它包含了一个标准的Maven项目结构:
- 标准的管理配置文件 pom.xml
- 原文路径 src/main/java/
- 测试文件路径 src/test/java/
在原文路径下的com.example包中有两个 class 文件,这个 Main 类主要是负责承接 Grizzly 容器,同时也为这个容器配置和部署 JAX-RS 应用。在同一个包内的另外一个类 MyResource 类是 JAX-RS 的一个实现的源代码,如下:
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
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;@Beforepublic void setUp() throws Exception {server = Main.startServer();Client c = ClientBuilder.newClient();target = c.target(Main.BASE_URI);}@Afterpublic void tearDown() throws Exception {server.stop();}/*** Test to see that the message "Got it!" is sent in the response.*/@Testpublic void testGetIt() {String responseMsg = target.path("myresource").request().get(String.class);assertEquals("Got it!", responseMsg);}}
在这个单元测试中(译者注:测试用到了 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。
