1. 程式人生 > >webService與Controller的用法

webService與Controller的用法

stl dep alt odi info out quest one change

一. RestFul WebService的創建:
本例使用SpringMVC來寫RestFul Web Service。

1.創建【Dynamic Web Prject】

2.添加代碼:
RestFul.java:

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


UserInfo.java

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


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. <!-- spring -->
  5. <servlet>
  6. <servlet-name>springMVC</servlet-name>
  7. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  8. <init-param>
  9. <param-name>contextConfigLocation</param-name>
  10. <param-value>/WEB-INF/springmvc-servlet.xml</param-value>
  11. </init-param>
  12. <load-on-startup>2</load-on-startup>
  13. </servlet>
  14. <servlet-mapping>
  15. <servlet-name>springMVC</servlet-name>
  16. <url-pattern>/</url-pattern>
  17. </servlet-mapping>
  18. </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. <context:annotation-config/>
  11. <mvc:default-servlet-handler/>
  12. <!-- 默認訪問跳轉到登錄頁面 -->
  13. <mvc:view-controller path="/" view-name="redirect:/getData" />
  14. <!-- Scans the classpath of this application for @Components to deploy as beans -->
  15. <context:component-scan base-package="com.webservice">
  16. <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
  17. </context:component-scan>
  18. <!-- 采用SpringMVC自帶的JSON轉換工具,支持@ResponseBody註解 -->
  19. <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  20. <property name="messageConverters">
  21. <list>
  22. <ref bean="stringHttpMessageConverter" />
  23. <ref bean="jsonHttpMessageConverter" />
  24. </list>
  25. </property>
  26. </bean>
  27. <bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
  28. <property name ="supportedMediaTypes">
  29. <list>
  30. <value>text/plain;charset=UTF-8</value>
  31. </list>
  32. </property>
  33. </bean>
  34. <!-- Configures the @Controller programming model -->
  35. <mvc:annotation-driven/>
  36. </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. <!-- Enables the Spring MVC @Controller programming model -->
  10. <annotation-driven />
  11. <!-- for processing requests with annotated controller methods and set Message Convertors from the list of convertors -->
  12. <beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
  13. <beans:property name="messageConverters">
  14. <beans:list>
  15. <beans:ref bean="jsonMessageConverter"/>
  16. </beans:list>
  17. </beans:property>
  18. </beans:bean>
  19. <!-- To convert JSON to Object and vice versa -->
  20. <beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
  21. </beans:bean>
  22. <context:component-scan base-package="net.javaonline.spring.restful" />
  23. </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. import java.util.ArrayList;
  3. import java.util.List;
  4. import org.apache.http.HttpEntity;
  5. import org.apache.http.NameValuePair;
  6. import org.apache.http.client.entity.UrlEncodedFormEntity;
  7. import org.apache.http.client.methods.CloseableHttpResponse;
  8. import org.apache.http.client.methods.HttpPost;
  9. import org.apache.http.impl.client.CloseableHttpClient;
  10. import org.apache.http.impl.client.HttpClients;
  11. import org.apache.http.message.BasicNameValuePair;
  12. import org.apache.http.util.EntityUtils;
  13. public class Rest{
  14. public static void main(String[] args){
  15. List<NameValuePair> params = new ArrayList<NameValuePair>();
  16. params.add(new BasicNameValuePair("userName", "Sun"));
  17. String url = "http://localhost:8080/RestWebService/getData";
  18. System.out.println(getRest(url, params));
  19. }
  20. public static String getRest(String url,List<NameValuePair> params){
  21. // 創建默認的httpClient實例.
  22. CloseableHttpClient httpclient = HttpClients.createDefault();
  23. // 創建httppost
  24. HttpPost httppost = new HttpPost(url);
  25. UrlEncodedFormEntity uefEntity;
  26. try{
  27. uefEntity = new UrlEncodedFormEntity(params, "UTF-8");
  28. httppost.setEntity(uefEntity);
  29. CloseableHttpResponse response = httpclient.execute(httppost);
  30. HttpEntity entity = response.getEntity();
  31. String json= EntityUtils.toString(entity, "UTF-8");
  32. int code= response.getStatusLine().getStatusCode();
  33. if(code==200 ||code ==204){
  34. return json;
  35. }
  36. }catch (Exception e){
  37. e.printStackTrace();
  38. }
  39. return "";
  40. }
  41. }


執行結果:

[plain] view plain copy
  1. Welcome Sun

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


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

轉載:http://blog.csdn.net/sunroyi666/article/details/51918675

webService與Controller的用法