RestFul WebService的创建和使用实例

来源:互联网 发布:电脑双系统切换软件 编辑:程序博客网 时间:2024/05/17 06:03

一. RestFul WebService的创建:
本例使用SpringMVC来写RestFul Web Service。

1.创建【Dynamic Web Prject】

2.添加代码:
RestFul.Java:

[java] view plain copy
  1. package com.webservice;  
  2.   
  3.   
  4. import java.io.OutputStreamWriter;  
  5. import java.io.PrintWriter;  
  6. import java.util.ArrayList;  
  7. import java.util.List;  
  8.   
  9.   
  10. import javax.servlet.http.HttpServletRequest;  
  11. import javax.servlet.http.HttpServletResponse;  
  12.   
  13.   
  14. import net.sf.json.JSONArray;  
  15.   
  16.   
  17. import org.springframework.stereotype.Controller;  
  18. import org.springframework.web.bind.annotation.PathVariable;  
  19. import org.springframework.web.bind.annotation.RequestMapping;  
  20. import org.springframework.web.bind.annotation.RequestMethod;  
  21. import org.springframework.web.bind.annotation.RequestParam;  
  22.   
  23.   
  24. @Controller  
  25. @RequestMapping(value = "/getData")  
  26. public class RestFul {  
  27.       
  28.     // http://localhost:8080/RestWebService/getData?userName=sun 方式的调用  
  29.     @RequestMapping  
  30.     public void printData1(HttpServletRequest request, HttpServletResponse response,   
  31.     @RequestParam(value="userName", defaultValue="User") String name) {  
  32.         String msg = "Welcome "+ name;  
  33.         printData(response, msg);  
  34.     }  
  35.   
  36.   
  37.     // http://localhost:8080/RestWebService/getData/Sun/Royi 方式的调用  
  38.     @RequestMapping(value = "/{firstName}/{lastName}")  
  39.     public void printData2(HttpServletRequest request, HttpServletResponse response,   
  40.         @PathVariable String firstName, @PathVariable String lastName) {  
  41.         String msg = "Welcome "+ firstName + " " + lastName;  
  42.         printData(response, msg);  
  43.     }  
  44.       
  45.     // 转换成HTML形式返回  
  46.     private void printData(HttpServletResponse response, String msg) {  
  47.         try {  
  48.             response.setContentType("text/html;charset=utf-8");  
  49.             response.setCharacterEncoding("UTF-8");  
  50.             PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));  
  51.             out.println(msg);  
  52.             out.close();  
  53.         } catch (Exception e) {    
  54.             e.printStackTrace();  
  55.         }  
  56.    }  
  57.   
  58.     // http://localhost:8080/RestWebService/getData/json?item=0 方式的调用  
  59.     @RequestMapping(value = "/json")  
  60.     public void printData3(HttpServletRequest request, HttpServletResponse response,   
  61.         @RequestParam(value="item", defaultValue="0") String item) {  
  62.         printDataJason(response, item);  
  63.     }  
  64.   
  65.   
  66.     // http://localhost:8080/RestWebService/getData/json/1 方式的调用  
  67.     @RequestMapping(value = "/json/{item}")  
  68.     public void printData4(HttpServletRequest request, HttpServletResponse response,   
  69.         @PathVariable String item) {  
  70.         printDataJason(response, item);  
  71.     }  
  72.       
  73.     // JSON格式化  
  74.     private void printDataJason(HttpServletResponse response, String item) {  
  75.         try {  
  76.            response.setContentType("text/html;charset=utf-8");  
  77.            response.setCharacterEncoding("UTF-8");  
  78.            PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));  
  79.              
  80.            List<UserInfo> uiList = new ArrayList<UserInfo>();  
  81.            for (int i=0; i<3; i++)  
  82.            {  
  83.                UserInfo ui = new UserInfo();  
  84.                ui.ID = i;  
  85.                ui.Name = "SUN" + i;  
  86.                ui.Position = "Position" + i;  
  87.                uiList.add(ui);  
  88.   
  89.                if (!item.equals("0")){  
  90.                    JSONArray jsonArr = JSONArray.fromObject(uiList.get(0));  
  91.                    out.println(jsonArr);  
  92.                }  
  93.                else{  
  94.                    JSONArray jsonArr = JSONArray.fromObject(uiList);  
  95.                    out.println(jsonArr);  
  96.                    //out.println(uiList);  
  97.                }  
  98.   
  99.                out.close();  
  100.            } catch (Exception e) {    
  101.                e.printStackTrace();    
  102.            }  
  103.         }  
  104. }  

UserInfo.java
[java] view plain copy
  1. package com.webservice;  
  2.   
  3. public class UserInfo{  
  4.       
  5.     Integer ID;  
  6.       
  7.     String Name;  
  8.       
  9.     String Position;  
  10.   
  11.     public Integer getID() {  
  12.         return ID;  
  13.     }  
  14.   
  15.     public void setID(Integer iD) {  
  16.         ID = iD;  
  17.     }  
  18.   
  19.     public String getName() {  
  20.         return Name;  
  21.     }  
  22.   
  23.     public void setName(String name) {  
  24.         Name = name;  
  25.     }  
  26.   
  27.     public String getPosition() {  
  28.         return Position;  
  29.     }  
  30.   
  31.     public void setPosition(String position) {  
  32.         Position = position;  
  33.     }  
  34.       
  35. }  

3.SpringMVC框架需要修改一些配置:
web.xml
[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <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">  
  3.   <display-name>RestWebService</display-name>  
  4.   
  5.     <!-- spring -->  
  6.     <servlet>  
  7.         <servlet-name>springMVC</servlet-name>  
  8.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  9.         <init-param>  
  10.             <param-name>contextConfigLocation</param-name>  
  11.             <param-value>/WEB-INF/springmvc-servlet.xml</param-value>  
  12.         </init-param>  
  13.         <load-on-startup>2</load-on-startup>  
  14.     </servlet>  
  15.   
  16.     <servlet-mapping>  
  17.         <servlet-name>springMVC</servlet-name>  
  18.         <url-pattern>/</url-pattern>  
  19.     </servlet-mapping>  
  20. </web-app>  

[html] view plain copy
  1. springmvc-servlet.xml:  
  2. <pre name="code" class="html"><?xml version="1.0" encoding="UTF-8"?>  
  3. <beans xmlns="http://www.springframework.org/schema/beans"  
  4.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.        xmlns:context="http://www.springframework.org/schema/context"  
  6.        xmlns:mvc="http://www.springframework.org/schema/mvc"  
  7.        xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  8.        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd  
  9.        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">  
  10.   
  11.     <context:annotation-config/>  
  12.       
  13.     <mvc:default-servlet-handler/>  
  14.   
  15.     <!-- 默认访问跳转到登录页面 -->  
  16.     <mvc:view-controller path="/" view-name="redirect:/getData" />  
  17.   
  18.     <!-- Scans the classpath of this application for @Components to deploy as beans -->  
  19.     <context:component-scan base-package="com.webservice">  
  20.         <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>  
  21.     </context:component-scan>  
  22.   
  23.     <!-- 采用SpringMVC自带的JSON转换工具,支持@ResponseBody注解 -->  
  24.     <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
  25.         <property name="messageConverters">  
  26.             <list>  
  27.                 <ref bean="stringHttpMessageConverter" />  
  28.                 <ref bean="jsonHttpMessageConverter" />  
  29.             </list>  
  30.         </property>  
  31.     </bean>  
  32.   
  33.     <bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">  
  34.         <property name ="supportedMediaTypes">  
  35.             <list>  
  36.                 <value>text/plain;charset=UTF-8</value>  
  37.             </list>  
  38.         </property>  
  39.     </bean>  
  40.   
  41.     <!-- Configures the @Controller programming model -->  
  42.     <mvc:annotation-driven/>  
  43.   
  44. </beans>  
rest-servlet.xml
[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans:beans xmlns="http://www.springframework.org/schema/mvc"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:beans="http://www.springframework.org/schema/beans"  
  5.     xmlns:context="http://www.springframework.org/schema/context"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd  
  7.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
  8.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">  
  9.    
  10.     <!-- Enables the Spring MVC @Controller programming model -->  
  11.     <annotation-driven />  
  12.    
  13.    <!-- for processing requests with annotated controller methods and set Message Convertors from the list of convertors -->  
  14.     <beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">  
  15.         <beans:property name="messageConverters">  
  16.             <beans:list>  
  17.                 <beans:ref bean="jsonMessageConverter"/>  
  18.             </beans:list>  
  19.         </beans:property>  
  20.     </beans:bean>  
  21.    
  22.     <!-- To  convert JSON to Object and vice versa -->  
  23.     <beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">  
  24.     </beans:bean>   
  25.    
  26.     <context:component-scan base-package="net.javaonline.spring.restful" />  
  27.    
  28. </beans:beans>  

4.用到的Jar包:
[plain] view plain copy
  1. commons-beanutils-1.8.0.jar  
  2. commons-collections-3.2.1.jar  
  3. commons-lang-2.5.jar  
  4. commons-logging-1.1.1.jar  
  5. commons-logging-1.1.3.jar  
  6. ezmorph-1.0.6.jar  
  7. jackson-all-1.9.0.jar  
  8. jackson-annotations-2.2.1.jar  
  9. jackson-core-2.2.1.jar  
  10. jackson-core-asl-1.7.1.jar  
  11. jackson-core-asl-1.8.8.jar  
  12. jackson-databind-2.2.1.jar  
  13. jackson-jaxrs-1.7.1.jar  
  14. jackson-mapper-asl-1.7.1.jar  
  15. jackson-mapper-asl-1.8.8.jar  
  16. jackson-module-jaxb-annotations-2.2.1.jar  
  17. json-lib-2.4-jdk15.jar  
  18. jstl-1.2.jar  
  19. servlet-api-2.5.jar  
  20. spring-aop-3.2.4.RELEASE.jar  
  21. spring-beans-3.2.4.RELEASE.jar  
  22. spring-context-3.2.4.RELEASE.jar  
  23. spring-core-3.2.4.RELEASE.jar  
  24. spring-expression-3.2.4.RELEASE.jar  
  25. spring-jdbc-3.2.4.RELEASE.jar  
  26. spring-orm-3.2.4.RELEASE.jar  
  27. spring-test-3.2.4.RELEASE.jar  
  28. spring-tx-3.2.4.RELEASE.jar  
  29. spring-web-3.2.4.RELEASE.jar  
  30. spring-webmvc-3.2.4.RELEASE.jar  

5.将RestWebService项目部署到Tomcat即可。

部署方法略

二. RestFul WebService的调用:
方法1:用HttpClient调用:
1.创建【Java Project】:

方法1:用HttpClient调用:
1.创建【Java Project】:

Rest.java:

[java] view plain copy
  1. package com.httpclientforrest;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5. import org.apache.http.HttpEntity;  
  6. import org.apache.http.NameValuePair;  
  7. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  8. import org.apache.http.client.methods.CloseableHttpResponse;  
  9. import org.apache.http.client.methods.HttpPost;  
  10. import org.apache.http.impl.client.CloseableHttpClient;  
  11. import org.apache.http.impl.client.HttpClients;  
  12. import org.apache.http.message.BasicNameValuePair;  
  13. import org.apache.http.util.EntityUtils;  
  14.   
  15. public class Rest{  
  16.       
  17.     public static void main(String[] args){  
  18.         List<NameValuePair> params = new ArrayList<NameValuePair>();  
  19.         params.add(new BasicNameValuePair("userName""Sun"));  
  20.           
  21.         String url = "http://localhost:8080/RestWebService/getData";  
  22.           
  23.         System.out.println(getRest(url, params));  
  24.     }  
  25.       
  26.     public static String getRest(String url,List<NameValuePair> params){  
  27.         // 创建默认的httpClient实例.      
  28.         CloseableHttpClient httpclient = HttpClients.createDefault();    
  29.         // 创建httppost      
  30.         HttpPost httppost = new HttpPost(url);   
  31.           
  32.         UrlEncodedFormEntity uefEntity;  
  33.           
  34.         try{  
  35.             uefEntity = new UrlEncodedFormEntity(params, "UTF-8");    
  36.             httppost.setEntity(uefEntity);  
  37.             CloseableHttpResponse response = httpclient.execute(httppost);    
  38.             HttpEntity entity = response.getEntity();    
  39.             String json= EntityUtils.toString(entity, "UTF-8");  
  40.             int code= response.getStatusLine().getStatusCode();  
  41.             if(code==200 ||code ==204){  
  42.                 return json;  
  43.             }  
  44.         }catch (Exception e){  
  45.             e.printStackTrace();  
  46.         }  
  47.           
  48.         return "";  
  49.     }  
  50. }  

执行结果:
[plain] view plain copy
  1. Welcome Sun  

[html] view plain copy
  1. 方法2:在JSP页面用JQuery调用:  
  2.   
  3. 1.创建【Dynamic Web Prject】  
  4. 相关配置文件和创建RestFulWebService相同。  
  5.   
  6. 2.建一个JSP页面:  
  7. rest.jsp:  
  8. <pre name="code" class="html"><%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>  
  9. <%  
  10. String path = request.getContextPath();  
  11. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  12. %>  
  13.   
  14. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  15. <html>  
  16.   <head>  
  17.     <base href="<%=basePath%>">  
  18.       
  19.     <title>Restfil WebService</title>  
  20.     <meta http-equiv="pragma" content="no-cache">  
  21.     <meta http-equiv="cache-control" content="no-cache">  
  22.     <meta http-equiv="expires" content="0">      
  23.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  24.     <meta http-equiv="description" content="This is Restfil WebService Test">  
  25.     <!-- 
  26.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  27.     -->  
  28.   </head>  
  29.     
  30.   <body>  
  31.     <div>  
  32.         <button id="callPrintDataWithoutParam">PrintDataWithoutParam</button>  
  33.         <button id="callPrintDataWithParam">PrintDataWithParam</button>  
  34.         <button id="callJsonWithoutParam">JsonWithoutParam</button>  
  35.         <button id="callJsonWithParam">JsonWithParam</button>  
  36.     </div>  
  37.     <div id='divContext'>  
  38.     </div>  
  39.   </body>  
  40.     
  41.   <script src="./script/jquery-1.8.3.min.js" type="text/javascript"></script>  
  42.   <script type="text/javascript">  
  43.     $(function(){  
  44.         $('#callPrintDataWithoutParam').click(function(event){  
  45.             document.getElementById("divContext").innerHTML = "";  
  46.    
  47.             var webserviceUrl="http://localhost:8080/RestWebService/getData" + "?userName=Sun";  
  48.             //var webserviceUrl="http://localhost:8080/RestWebService/getData";  
  49.   
  50.             $.ajax({  
  51.                 type: 'POST',  
  52.                 contentType: 'application/json',  
  53.                 url: webserviceUrl,  
  54.                 //data: {"userName":"Sun"},  
  55.                 dataType: 'html',  
  56.                 success: function (result) {  
  57.             document.getElementById("divContext").innerHTML = result;  
  58.                 },  
  59.                 error:function(){  
  60.                     alert("error");  
  61.                 }  
  62.             });  
  63.               
  64.             //取消事件的默认行为。比如:阻止对表单的提交。IE下不支持,需用window.event.returnValue = false;来实现  
  65.             event.preventDefault();  
  66.   
  67.         });  
  68.       
  69.     $('#callPrintDataWithParam').click(function(event){  
  70.             document.getElementById("divContext").innerHTML = "";  
  71.             var webserviceUrl="http://localhost:8080/RestWebService/getData" + "/Sun/Royi";  
  72.               
  73.             $.ajax({  
  74.                 type: 'POST',  
  75.                 contentType: 'application/json',  
  76.                 url: webserviceUrl,  
  77.                 //data: "{firstName:Sun,lastName:Royi}",  
  78.                 dataType: 'html',  
  79.                 success: function (result) {  
  80.             document.getElementById("divContext").innerHTML = result;  
  81.                 },  
  82.                 error:function(){  
  83.                     alert("error");  
  84.                 }  
  85.             });  
  86.               
  87.             event.preventDefault();   
  88.         });  
  89.           
  90.         $('#callJsonWithoutParam').click(function(event){  
  91.             document.getElementById("divContext").innerHTML = "";  
  92.               
  93.             $.ajax({  
  94.                 type: 'POST',  
  95.                 contentType: 'application/json',  
  96.                 url: 'http://localhost:8080/RestWebService/getData/json',  
  97.                 data: "{}",  
  98.                 dataType: 'json',  
  99.                 success: function (result) {  
  100.                     document.getElementById("divContext").innerHTML = "json:" + "<br>";  
  101.             document.getElementById("divContext").innerHTML += result + "<br><br>";  
  102.                     document.getElementById("divContext").innerHTML += "Changed:" + "<br>";  
  103.                           
  104.                     for(i=0;i<result.length;i++){  
  105.                 document.getElementById("divContext").innerHTML += "ID:" + result[i].ID + "<br>";  
  106.                 document.getElementById("divContext").innerHTML += "Name:" + result[i].name + "<br>";  
  107.                         document.getElementById("divContext").innerHTML += "position:" + result[i].position + "<br>";  
  108.                         document.getElementById("divContext").innerHTML += "-------------------------------<br>";  
  109.                     }  
  110.                 },  
  111.                 error:function(){  
  112.                     alert("error");  
  113.                 }  
  114.             });  
  115.               
  116.             event.preventDefault();   
  117.         });  
  118.           
  119.         $('#callJsonWithParam').click(function(event){  
  120.         document.getElementById("divContext").innerHTML = "";  
  121.               
  122.             $.ajax({  
  123.                 type: 'POST',  
  124.                 contentType: 'application/json',  
  125.                 url: 'http://localhost:8080/RestWebService/getData/json/1',  
  126.                 //data: '{"item":1}',  
  127.                 dataType: 'html',  
  128.                 success: function (result) {  
  129.             document.getElementById("divContext").innerHTML = result;  
  130.                 },  
  131.                 error:function(){  
  132.                     alert("error");  
  133.                 }  
  134.             });  
  135.               
  136.             event.preventDefault();   
  137.         });  
  138.       
  139.     });  
  140.   </script>  
  141. </html>  
  142. </span>  

执行结果:PrintDataWithoutParam:
[plain] view plain copy
  1. Welcome Sun  
[html] view plain copy
  1. PrintDataWithParam:  
  2. <pre name="code" class="plain">Welcome Sun Royi  

JsonWithoutParam:

[plain] view plain copy
  1. json:  
  2. [object Object],[object Object],[object Object]  
  3.   
  4. Changed:  
  5. ID:0  
  6. Name:SUN0  
  7. position:Position0  
  8. -------------------------------  
  9. ID:1  
  10. Name:SUN1  
  11. position:Position1  
  12. -------------------------------  
  13. ID:2  
  14. Name:SUN2  
  15. position:Position2  
  16. -------------------------------  


JsonWithParam:

[plain] view plain copy
  1. [{"ID":0,"name":"SUN0","position":"Position0"}]  


相关文章:

WSDL WebService和RestFul WebService的个人理解:
http://blog.csdn.net/sunroyi666/article/details/51939802


WSDL WebService的创建和使用实例:

http://blog.csdn.net/sunroyi666/article/details/51917991

WSDL WebService和RestFul WebService的Sample代码:
http://download.csdn.net/detail/sunroyi666/9577143
原创粉丝点击