1.用Ctrl+空格调出Spotlight搜索,输入ter调出终端窗口

maven archetype 和 Maven是什么区别 maven create from archetype_Test


2.在终端窗口进入将创建jersey项目的目录:

maven archetype 和 Maven是什么区别 maven create from archetype_java_02


3.输入如下命令,创建一个名为的simple-service项目:

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.16

maven archetype 和 Maven是什么区别 maven create from archetype_HTTP_03


maven archetype 和 Maven是什么区别 maven create from archetype_maven jersey mysql_04


4.在Eclipse中import该maven项目:

maven archetype 和 Maven是什么区别 maven create from archetype_java_05


5.在你的项目里面随意调整 pom.xml 内的 groupId,包名和版本号就可以成为一个新的项目。

6如果用 Jersey maven archetype 成功创建了这个项目,那么在你当前的路径下就已经创建了一个名为simple-service项目。它包含了一个标准的Maven项目结构:

• 标准的管理配置文件 pom.xml

• 原文路径 src/main/java/

• 测试文件路径 src/test/java/

在原文路径下的com.example包中有两个 class 文件,这个 Main 类主要是负责承接 Grizzly 容器,同时也为这个容器配置和部署 JAX-RS 应用。在同一个包内的另外一个类 MyResource 类是 JAX-RS 的一个实现的源代码,如下:

packagecom.example;importjavax.ws.rs.GET;importjavax.ws.rs.Path;importjavax.ws.rs.Produces;importjavax.ws.rs.core.MediaType;/*** Root resource (exposed at "myresource" path)*/@Path("myresource")public classMyResource {/*** Method handling HTTP GET requests. The returned object will be sent
* to the client as "text/plain" media type.
*
*@returnString that will be returned as a text/plain response.*/@GET
@Produces(MediaType.TEXT_PLAIN)publicString getIt() {return "Got it!";
}
}
一个 JAX-RS 资源是一个可以处理绑定了资源的URI的HTTP请求的带有注解的POJO,详细内容可以看第三章。在我们的例子中,单一的资源暴露了一个公开的方法,能够处理HTTP GET请求,绑定在/myresource URI路径下,可以产生媒体类型为“text/plain”的响应消息。在这个示例中,资源返回相同的“Got it!”应对所有客户端的要求。
在src/test/java目录下的 MyResourceTest 类是对 MyResource 的单元测试,他们具有相同的包com.example
packagecom.example;importjavax.ws.rs.client.Client;importjavax.ws.rs.client.ClientBuilder;importjavax.ws.rs.client.WebTarget;importorg.glassfish.grizzly.http.server.HttpServer;
...public classMyResourceTest {privateHttpServer server;privateWebTarget target;
@Beforepublic void setUp() throwsException {
server=Main.startServer();
Client c=ClientBuilder.newClient();
target=c.target(Main.BASE_URI);
}
@Afterpublic void tearDown() throwsException {
server.stop();
}/*** Test to see that the message "Got it!" is sent in the response.*/@Testpublic voidtestGetIt() {
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字符串类型被读到。在测试方法的第二行,响应的内容(从服务器返回的字符串)跟测试断言预期短语比较