标签:
最近因项目需求,开始学习WebServices。
1、开发环境:
MyEclipse2013
2、客户端发送的JSON数据格式为
{persons:[{"name":"a","age":1},{"name":"b","age":2}],"sex":"male"}(POST请求方式使用)
{"name":"abc","age":123}(PUT请求方式使用)
3、服务端返回的JSON数据格式为
{"message":"OK"}
4、客户端请求方式包括
POST、PUT、DELETE、GET
5、服务端参数来自HTTP请求的位置包括
URL路径、URL查询参数
第一步:建立WebServices工程,如图
 
直接Finish就好,也可以自己Next一下看看有哪些设置。
 
第二步:添加额外Jar包,包括
org.json
gson
org.restlet.ext.jaxrs
org.restlet.ext.json
org.restlet.ext.servlet
org.restlet
第二步:创建Person类
[java] view plaincopy
- package server;  
-   
- public class Person {  
-     private String name;  
-     private int age;  
-   
-     public Person(String name, int age) {  
-         this.name = name;  
-         this.age = age;  
-     }  
-   
-     public Person() {  
-     }  
-   
-     public void setName(String name) {  
-         this.name = name;  
-     }  
-   
-     public void setAge(int age) {  
-         this.age = age;  
-     }  
-   
-     public String getName() {  
-         return this.name;  
-     }  
-   
-     public int getAge() {  
-         return this.age;  
-     }  
-   
-     public String toString() {  
-         return "name=" + this.name + "|age=" + this.age;  
-     }  
- }  
 
第三步:创建MyResponse类
[java] view plaincopy
- package server;  
-   
- public class MyResponse {  
-     private String message;  
-   
-     public MyResponse(String message) {  
-         this.message = message;  
-     }  
-   
-     public MyResponse() {  
-     }  
-   
-     public void setMessage(String message) {  
-         this.message = message;  
-     }  
-   
-     public String getMessage() {  
-         return this.message;  
-     }  
-   
-     public String toString() {  
-         return "message=" + this.message;  
-     }  
- }  
第四步:创建PersonResource类
[java] view plaincopy
- package server;  
-   
- import java.util.List;  
-   
- import javax.ws.rs.Consumes;  
- import javax.ws.rs.DELETE;  
- 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.QueryParam;  
-   
- import org.json.JSONArray;  
- import org.json.JSONException;  
- import org.json.JSONObject;  
-   
- import com.google.gson.Gson;  
- import com.google.gson.reflect.TypeToken;  
-   
- @Path("/person")  
- public class PersonResource {  
-     @POST  
-     // 设置请求方式  
-     @Path("/post")  
-     // 设置请求路径  
-     @Consumes("application/json")  
-     // 设置接收数据格式  
-     @Produces("application/json")  
-     // 设置返回数据格式  
-     public MyResponse post(JSONObject request) {  
-         MyResponse response = new MyResponse("OK");  
-   
-         // 获取persons数组  
-         JSONArray persons;  
-         String sex;  
-         try {  
-             persons = request.getJSONArray("persons");  
-             sex = request.getString("sex");  
-         } catch (JSONException e) {  
-             e.printStackTrace();  
-   
-             response.setMessage("ERROR");  
-             return response;  
-         }  
-   
-         // 获取各person信息  
-         int count = persons.length();  
-         Gson gson = new Gson();  
-         List<Person> ps = gson.fromJson(persons.toString(),  
-                 new TypeToken<List<Person>>() {  
-                 }.getType());  
-         for (int i = 0; i < count; i++) {  
-             Person p = ps.get(i);  
-             System.out.println(p);  
-         }  
-         System.out.println(sex);  
-         return response;  
-     }  
-   
-     @PUT  
-     @Path("/put")  
-     @Consumes("application/json")  
-     @Produces("application/json")  
-     public MyResponse put(JSONObject request) {  
-         MyResponse response = new MyResponse("OK");
-         Gson gson = new Gson();  
-         Person p = gson.fromJson(request.toString(), Person.class);  
-         System.out.println(p);  
-         return response;  
-     }  
-   
-     @DELETE  
-     @Path("/delete")  
-     @Produces("application/json")  
-     // 从URL查询参数中获取参数  
-     public MyResponse delete(@QueryParam("name") List<String> name,  
-             @QueryParam("age") int age) {  
-         MyResponse response = new MyResponse("OK");
-         System.out.println(name);  
-         System.out.println(age);  
-         return response;  
-     }  
-   
-     @GET  
-     @Path("/{name}/get")  
-     @Produces("application/json")  
-     // 从URL路径中获取参数  
-     public MyResponse get(@PathParam("name") String name) {  
-         MyResponse response = new MyResponse("OK");
-         System.out.println(name);  
-         return response;  
-     }  
- }  
 
第五步:创建PersonApplication类
[java] view plaincopy
- package app;  
-   
- import java.util.HashSet;  
- import java.util.Set;  
-   
- import javax.ws.rs.core.Application;  
-   
- import server.PersonResource;  
-   
- public class PersonApplication extends Application {  
-     @Override  
-     public Set<Class<?>> getClasses() {  
-         Set<Class<?>> rrcs = new HashSet<Class<?>>();  
-         // 绑定PersonResource。有多个资源可以在这里绑定。  
-         rrcs.add(PersonResource.class);  
-         return rrcs;  
-     }  
- }  
 
第六步:创建RestJaxRsApplication类
[java] view plaincopy
- package app;  
-   
- import org.restlet.Context;  
- import org.restlet.ext.jaxrs.JaxRsApplication;  
-   
- public class RestJaxRsApplication extends JaxRsApplication {  
-     public RestJaxRsApplication(Context context) {  
-         super(context);  
-         // 将PersonApplication加入了运行环境中,如果有多个Application可以在此绑定  
-         this.add(new PersonApplication());  
-     }  
- }  
 
第七步:修改web.xml,添加如下内容
[html] view plaincopy
- <context-param>  
-   <param-name>org.restlet.application</param-name>  
-   <param-value>app.RestJaxRsApplication</param-value>  
- </context-param>  
- <servlet>  
-   <servlet-name>PersonServlet</servlet-name>  
-   <servlet-class>org.restlet.ext.servlet.ServerServlet</servlet-class>  
- </servlet>  
- <servlet-mapping>  
-   <servlet-name>PersonServlet</servlet-name>  
-   <url-pattern>/*</url-pattern>  
- </servlet-mapping>  
本示例工程的web.xml的完整代码如下,可供参考
[html] view plaincopy
- <?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">  
-   <display-name>EXP</display-name>  
-   <context-param>  
-     <param-name>org.restlet.application</param-name>  
-     <param-value>app.RestJaxRsApplication</param-value>  
-   </context-param>  
-   <servlet>  
-     <servlet-name>PersonServlet</servlet-name>  
-     <servlet-class>org.restlet.ext.servlet.ServerServlet</servlet-class>  
-   </servlet>  
-   <servlet-mapping>  
-     <servlet-name>PersonServlet</servlet-name>  
-     <url-pattern>/*</url-pattern>  
-   </servlet-mapping>  
- </web-app>  
 
第八步:编写客户端
[java] view plaincopy
- package test;  
-   
- import java.io.IOException;  
- import java.util.ArrayList;  
- import java.util.List;  
-   
- import org.json.JSONArray;  
- import org.json.JSONException;  
- import org.json.JSONObject;  
- import org.junit.Test;  
- import org.restlet.data.MediaType;  
- import org.restlet.resource.ClientResource;  
- import org.restlet.resource.ResourceException;  
-   
- import server.Person;  
-   
- import com.google.gson.Gson;  
-   
- public class Client {  
-     public static String url = "http://127.0.0.1:8080/EXP/person";  
-   
-     @Test  
-     public void testPost() {  
-         ClientResource client = new ClientResource(url + "/post");  
-         try {  
-             Gson gson = new Gson();  
-             List<Person> ps = new ArrayList<Person>();  
-             for (int i = 0; i < 2; i++) {  
-                 Person p = new Person();  
-                 p.setName(String.valueOf(‘a‘ + i));  
-                 p.setAge(i + 1);  
-                 ps.add(p);  
-             }  
-             JSONArray persons = new JSONArray(gson.toJson(ps));  
-             JSONObject json = new JSONObject("{\"persons\":" + persons  
-                     + ",\"sex\":male}");  
-             String result = client.post(json, MediaType.APPLICATION_JSON)  
-                     .getText();  
-             System.out.println("This is POST...");  
-             System.out.println(result);  
-         } catch (Exception e) {  
-             e.printStackTrace();  
-         }  
-     }  
-   
-     @Test  
-     public void testPut() {  
-         ClientResource client = new ClientResource(url + "/put");  
-         JSONObject json;  
-         try {  
-             json = new JSONObject("{\"name\":\"abc\",\"age\":123}");  
-             String result = client.put(json, MediaType.APPLICATION_JSON)  
-                     .getText();  
-             System.out.println("This is PUT...");  
-             System.out.println(result);  
-         } catch (JSONException e) {  
-             e.printStackTrace();  
-         } catch (ResourceException e) {  
-             e.printStackTrace();  
-         } catch (IOException e) {  
-             e.printStackTrace();  
-         }  
-     }  
-   
-     @Test  
-     public void testDelete() {  
-         ClientResource client = new ClientResource(url  
-                 + "/delete?name=xyz,ijk&age=456");  
-         try {  
-             String result;  
-             result = client.delete().getText();  
-             System.out.println("This is DELETE...");  
-             System.out.println(result);  
-         } catch (ResourceException e) {  
-             e.printStackTrace();  
-         } catch (IOException e) {  
-             e.printStackTrace();  
-         }  
-     }  
-   
-     @Test  
-     public void testGet() {  
-         ClientResource client = new ClientResource(url + "/ijk/get");  
-         try {  
-             System.out.println("This is GET...");  
-             System.out.println(client.get().getText());  
-         } catch (ResourceException e) {  
-             e.printStackTrace();  
-         } catch (IOException e) {  
-             e.printStackTrace();  
-         }  
-     }  
- }  
 
第九步:启动Tomcat,发布服务
若无报错(启动和发布都没报错)则说明服务发布成功。
 
第十步:运行客户端,查看演示效果
可在客户端与服务端的控制台查看输出。
 
至此,整个示例工程结束。其中包含了主要的请求方法和参数获得方法,传输的数据格式也采用流行的JSON格式(也可以使用XML,各位可自行查找相关资料)。
 
转载与http://blog.csdn.net/nani_z/article/details/12870887
MyEclipse开发JAX-RS架构WebServices收发JSON数据格式
标签:
原文地址:http://www.cnblogs.com/chenyq/p/4353828.html