您的位置:首页 > 其它

Jersey入门到放弃-1

2017-04-11 00:00 225 查看
摘要: 搭建基于JavaSE的jersey项目

本节讲解如何快速使用jersey构建Restful Webservice,使用的是轻量级的Grizzly服务器发布服务。

一般情况下我们使用maven时,依赖的jar都使用稳定版,不会使用snapshot版,但如果你想使用jersey的snapshot版的话,请引入以下配置到pom文件中:

<repository>
<id>snapshot-repository.java.net</id>
<name>Java.net Snapshot Repository for Maven</name>
<url>https://maven.java.net/content/repositories/snapshots/</url>
<layout>default</layout>
</repository>



开始搭建项目

1、使用以下命令创建一个基于Grizzly的jersey项目(也可以在Eclipse中安装jersey插件生成):

mvnarchetype: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.可以使用mvnclean test/run as -Junit Test运行MyResourceTest 测试程序

4.使用
mvn
exec:java/run as -Java Application运行
Main程序

5.打开浏览器访问http://localhost:8080/myapp/myresource就可以访问RestFul API了,也可以使用访问Jersey提供的wadl文档(一种类似于wsdl的文档), 地址 http://localhost:8080/myapp/application.wadl
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Jersey JAX-RS