spring和maven的搭建参考相关文档。本文只介绍与jersey有关配置。
一、jersey在maven中的依赖包
- <!-- jersey -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.8</version></dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.8</version></dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.8</version></dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0-m10</version></dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>1.1.1</version></dependency>
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.3.1</version></dependency>
<!-- jersey end -->
需要json,加入以下
<!-- json-->
<dependency>
<groupId>com.sun.jersey</groupId><artifactId>jersey-json</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId>
<version>1.8.8</version>
</dependency>
<!-- json-->
尽量保持包版本的一致
二、整合spring
1、 引入整合包,注意版本
<!-- jersey spring -->
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-spring</artifactId>
<version>1.8</version>
<!-- 去除自带的spring版本 -->
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
<exclusion>
<artifactId>spring-web</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- jersey spring end-->
2、web.xml配置
所有rest请求都经过spring过滤
<!-- jersey spring --><dependency> <groupId>com.sun.jersey.contribs</groupId> <artifactId>jersey-spring</artifactId> <version>1.8</version> <!-- 去除自带的spring版本 --> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> </exclusion> <exclusion> <artifactId>spring-web</artifactId> <groupId>org.springframework</groupId> </exclusion> </exclusions></dependency><!-- jersey spring end--><dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope></dependency>
三、编写服务端资源
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class User implements java.io.Serializable{
private static final long serialVersionUID = 1L;
private String userName = "";
private int age = 0;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return "name:"+ userName + " age:" + age;
}
}
import javax.ws.rs.FormParam;import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement //表示可以被转换为xml或json格式
public class Home implements java.io.Serializable {@FormParam("roomno")
private int roomNo;
@FormParam("address")
private String address;
private String longtime;
public int getRoomNo() {
return roomNo;
}
public void setRoomNo(int roomNo) {
this.roomNo = roomNo;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getLongtime() {
return longtime;
}
public void setLongtime(String longtime) {
this.longtime = longtime;
}
public String toString() {
return "roomNo:" + roomNo + " address:" + address + " longtime:" + longtime;
}}
2、编写资源接口
import javax.ws.rs.BeanParam;import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
@Component //定义此类为spring组件,即bean类.
@Scope("prototype") //Spring会针对每一个request请求都生成新的Jersey服务类实例,此方法不需要配置Spring RequsetContextListener@Path("/restresource")
public class TestRestResource {
1、无参数返回json格式,如返回xml,将Produces参数修改为MediaType.APPLICATION_XML
@GET@Path("/getUser")
@Produces(MediaType.APPLICATION_JSON)
public User getUser() {
User user = new User();
user.setUserName("sed");
user.setAge(29);
return user;
}
2、@PathParam("id")获取URI中指定规则的参数
@GET
@Path("getUser/{id}")
@Produces(MediaType.TEXT_PLAIN)
public String getUserId(@PathParam("id") String id) {
return id;
}
3、@QueryParam 用于获取GET请求中的查询参数
@GET
@Path("getId")
@Produces(MediaType.TEXT_PLAIN)
public String getId(@QueryParam("id") String id)
{
return id;
}
4、输入参数为xml格式,输出为json格式。可以根据需要切换produces和consumes的类型
@POST
@Path("insertUser")
@Produces(MediaType.APPLICATION_JSON) //指定发送请求的 MIME 类型
@Consumes(MediaType.APPLICATION_XML) //指定响应所能接受的 MIME 类型
public User insertuser(User user) {
return user;
}
5、BeanParam 当请求参数很多时,比如客户端提交一个修改用户的PUT请求,请求中包含很多项用户信息
@PUT
@Path("insertUserFromBean")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public User inserthome(@BeanParam User user) {
return user;
}6、@FormParam 从POST请求的表单参数中获取数据
@POST
@Path("insertUserFromForm")
@Consumes("application/x-www-form-urlencoded")
@Produces(MediaType.TEXT_PLAIN)
public String insertuser(@FormParam("username") String userName, @FormParam("age") int age) {
User user = new User();user.setUserName(userName);user.setAge(age);return user.toString();
}7、多参数传递
@POST
@Path("map")
@Produces(MediaType.TEXT_PLAIN)
public String getMap(MultivaluedMap<String, String> formParams) {
String result = "who:" + formParams.getFirst("who") + " ; what:"+formParams.getFirst("what");
return formParams.toString();
}
8、
@DELETE
@Path("deleteUser/{id}")
@Produces(MediaType.TEXT_PLAIN)
public String deleteUser(@PathParam("id") String id) {
//System.out.println(uriInfo.getAbsolutePath().toString());
return "delete " + id;
}
}
四、客户端调用
private static WebResource getWr(String USER_URL) {
Client c = Client.create(); //创建一个 com.sun.jersey .api.client.Client 类的实例
WebResource wr = c.resource(USER_URL); // 建了一个 WebResponse 对象return wr;
}
1、调用getUser
代码:
String USER_URL = "http://localhost:8000/restful/services/restresource/getUser";System.out.println(getWr(USER_URL).get(String.class));
输出:
{"userName":"sed","age":29}
2、调用getUser/{id}
代码:String USER_URL = "http://localhost:8000/restful/services/restresource/getUser";String result = getWr(USER_URL).path("hnsed").get(String.class) ;System.out.println(result);输出:
hnsed
3、调用getId
代码:String USER_URL = "http://localhost:8000/restful/services/restresource/getId";String result = getWr(USER_URL).queryParam("id", "109").get(String.class);System.out.println(result);输出:
109
4、调用insertUser
代码:User user = new User();user.setUserName("hndes");user.setAge(39);String USER_URL = "http://localhost:8000/restful/services/restresource/insertUser";MultivaluedMapImpl params = new MultivaluedMapImpl();params.add("user", user);String result = getWr(USER_URL).entity(user,MediaType.APPLICATION_XML).post(String.class);System.out.println(result);
输出:
{"userName":"hndes","age":39}
5、调用insertUserFromBean
代码:String USER_URL = "http://localhost:8000/restful/services/restresource/insertUserFromBean";String json = "{\"userName\":\"szh\",\"age\":\"6\"}";System.out.println(getWr(USER_URL).entity(json,MediaType.APPLICATION_JSON).put(String.class));输出:
{"userName":"szh","age":6}
6、调用insertUserFromForm
代码:String USER_URL = "http://localhost:8000/restful/services/restresource/insertUserFromForm";Form form = new Form();form.add("username", "sed");form.add("age",39);//ClientResponse 对象代表了一个客户端收到的 HTTP 响应。ClientResponse response = getWr(USER_URL).type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, form);int status = response.getStatus(); //获取对应请求的 HTTP 状态码System.out.println(response.getEntity(String.class));输出:
name:sed age:39
7、调用map
代码:
MultivaluedMap<String, String> params = new MultivaluedMapImpl();params.add("who", "sed");params.add("what","dohousework");params.add("how","good");params.add("where","hk");params.add("when","long time");String USER_URL = "http://localhost:8000/restful/services/restresource/map";String result = getWr(USER_URL).post(String.class,params);System.out.println(result);
输出:
{what=[dohousework], how=[good], when=[long time], where=[hk], who=[sed]}
8、调用deleteUser
代码:String USER_URL = "http://localhost:8000/restful/services/restresource/deleteUser";String result = getWr(USER_URL).path("109").delete(String.class);System.out.println(result);输出:
delete 109
注:1、Client 类是创建一个 RESTful Web Service 客户端的主要配置点。你可以使用它来配置不同的客户端属性和功能,并且指出使用哪个资源提供者。创建一个 Client 类的实例是一个比较昂贵的操作,所以尽量避免创建一些不需要的客户端实例。比较好的方式是尽可能地复用已经存在的实例。
2、通过使用 WebResource 对象来创建要发送到 Web 资源的请求,以及处理从 Web 资源返回的响应。例如,你可以使用 WebResource 对象来发送 HTTP GET、PUT、POST 以及 DELETE 请求
转载地址:http://ekekyn.blog.163.com/blog/static/313887320151294452322/