基于网上的例子进行了Jersey的实战
1.在eclipse中新建动态web工程JerseyWS
2.拷贝jar包到lib目录
asm-3.3.1.jar
jackson-core-asl-1.9.2.jar
jackson-jaxrs-1.9.2.jar
jackson-mapper-asl-1.9.2.jar
jackson-xc-1.9.2.jar
jersey-bundle-1.18.jar
jersey-client-1.17.1.jar
jersey-core-1.17.1.jar
jersey-json-1.18.jar
jersey-server-1.17.1.jar
jersey-servlet-1.17.1.jar
jsr311-api-1.1.1.jar
工程截图
3.src下创建com.eviac.blog.restws包,创建类Track.java和TrackService.java
==========
Track.java
==========
package com.eviac.blog.restws;
public class Track {
Integer id;
String title;
String singer;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSinger() {
return singer;
}
public void setSinger(String singer) {
this.singer = singer;
}
@Override
public String toString(){
return "Track [title="+title+", singer="+singer+"]";
}
}
==========
TrackService.java
==========
package com.eviac.blog.restws;import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/trackService")
public class TrackService {
static Track track = null;
@GET
@Path("/get")
@Produces(MediaType.APPLICATION_JSON)
public Track getTrackInJSON(){
if(null == this.track){
Track track = new Track();
track.setTitle("Enter Sandman");
track.setSinger("Metallica");
return track;
}
return this.track;
}
@POST
@Path("/post")
public Response createTrackInJSON(Track track){
this.track = track;
String result = "Track saved : " + track;
return Response.status(201)
.entity(result)
.type(MediaType.TEXT_PLAIN)
.build();
}
@PUT
@Path("/put/{id}")
public Response updateTrackInfoInJSON(@PathParam("id") Integer id, Track track){
int response_code = 204;
String result = "Track updated : " + track;
if(null == this.track || this.track.getId() != id){
response_code = 201;
result = "Track saved : " + track;
}
this.track = track;
return Response.status(response_code)
.entity("response_code "+response_code+", "+result)
.type(MediaType.TEXT_PLAIN)
.build();
// return Response.ok().entity("response_code "+response_code+", "+result).type(MediaType.TEXT_PLAIN).build();
}
}
4.配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>JerseyWS</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<display-name>RESTfulWS</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.eviac.blog.restws</param-value>
</init-param>
<!-- turn the JSONConfiguration.FEATURE_POJO_MAPPING feature on -->
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
5.启动tomcat,在浏览器中输入http://localhost/JerseyWS/rest/trackService/get/,出现如下界面则服务端启动成功
5.创建普通java工程JerseyWSClient
6.新建lib目录,拷贝jar包到lib目录
jersey-bundle-1.18.jar
jersey-client-1.17.1.jar
jersey-core-1.17.1.jar
7.在src下新建com.track.client包,新建类TrackClient.java===========
TrackClient.java
=============
package com.track.client;
import javax.ws.rs.core.MediaType;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
public class TrackClient {
public static void main(String[] args) {
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE );
Client client = Client.create(clientConfig);
String input = "{\"id\":1,\"singer\":\"Metallica\",\"title\":\"Fade To Black\"}";
WebResource r = client.resource("http://localhost/JerseyWS/rest/trackService/post/");
input = postTrack2Remoute(r, input);
getRemouteTrack(client);
input = "{\"id\":2,\"singer\":\"Metallica\",\"title\":\"Enter Sandman\"}";
postTrack2Remoute2(input, r);
getRemouteTrack(client);
input = "{\"id\":3,\"singer\":\"Metallica\",\"title\":\"Creeping Death\"}";
postTrack2Remoute3(input, r);
getRemouteTrack2(client);
input = "{\"id\":2,\"singer\":\"Metallica\",\"title\":\"Creeping Death333\"}";
r = client.resource("http://localhost/JerseyWS/rest/trackService/put/2");
putTrack2Remoute(input, r);
getRemouteTrack2(client);
}
/**
* post提交3
* @param input
* @param r
*/
private static void postTrack2Remoute3(String input, WebResource r) {
String response3 = r.accept(MediaType.APPLICATION_JSON, MediaType.TEXT_XML)
.entity(input, MediaType.APPLICATION_JSON)
.post(String.class);
System.out.println(response3);
}
/**
* 用于更新
* @param input
* @param r
*/
private static void putTrack2Remoute(String input, WebResource r) {
String response3 = r.accept(MediaType.APPLICATION_JSON, MediaType.TEXT_XML)
.entity(input, MediaType.APPLICATION_JSON)
.put(String.class);
System.out.println(response3);
}
/**
* post提交2
* @param input
* @param r
*/
private static void postTrack2Remoute2(String input, WebResource r) {
String response2 = r.accept(MediaType.APPLICATION_JSON, MediaType.TEXT_XML)
.type(MediaType.APPLICATION_JSON)
.post(String.class, input);
System.out.println(response2);
}
/**
* post提交1
* @param r
* @param input
* @return
*/
private static String postTrack2Remoute(WebResource r, String input) {
ClientResponse response = r.type(MediaType.APPLICATION_JSON)
.post(ClientResponse.class, input);
if(201 != response.getStatus()){
throw new RuntimeException("Failed : HTTP error code : "+response.getStatus());
}
System.out.println("\nOutput from Server ..................\n");
String output = response.getEntity(String.class) ;
System.out.println(output);
return input;
}
/**
* get请求
* @param client
*/
private static void getRemouteTrack(Client client) {
//获取请求响应状态消息
WebResource resource = client.resource("http://localhost/JerseyWS/rest/trackService/get/");
String returnMsg = resource.accept(MediaType.APPLICATION_JSON, MediaType.TEXT_XML)
.get(ClientResponse.class)
.toString();
System.out.println(returnMsg);
//获取调用方法的返回结果
String returnMsg2 = resource.accept(MediaType.APPLICATION_JSON, MediaType.TEXT_XML)
.get(String.class);
System.out.println(returnMsg2);
System.out.println("\n");
}
private static void getRemouteTrack2(Client client){
WebResource resource = client.resource("http://localhost/JerseyWS/rest/trackService/get/");
ClientResponse clientResponse = resource.accept(MediaType.APPLICATION_JSON, MediaType.TEXT_XML)
.get(ClientResponse.class);
System.out.println("response status : " + clientResponse.getStatus());
System.out.println("response result : " + clientResponse.getEntity(String.class));
System.out.println("\n");
}
}
8运行TrackClient.java的main方法,输出如下结果
Output from Server ..................
Track saved : Track [title=Fade To Black, singer=Metallica]
GET http://localhost/JerseyWS/rest/trackService/get/ returned a response status of 200 OK
{"id":1,"title":"Fade To Black","singer":"Metallica"}
Track saved : Track [title=Enter Sandman, singer=Metallica]
GET http://localhost/JerseyWS/rest/trackService/get/ returned a response status of 200 OK
{"id":2,"title":"Enter Sandman","singer":"Metallica"}
Track saved : Track [title=Creeping Death, singer=Metallica]
response status : 200
response result : {"id":3,"title":"Creeping Death","singer":"Metallica"}
response_code 201, Track saved : Track [title=Creeping Death333, singer=Metallica]
response status : 200
response result : {"id":2,"title":"Creeping Death333","singer":"Metallica"}