分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 软件开发

webService与Controller的用法

发布时间:2023-09-06 01:16责任编辑:彭小芳关键词:暂无标签

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

1.创建【Dynamic Web Prject】

2.添加代码:
RestFul.java:

[java]view plaincopy
  1. packagecom.webservice;
  2. importjava.io.OutputStreamWriter;
  3. importjava.io.PrintWriter;
  4. importjava.util.ArrayList;
  5. importjava.util.List;
  6. importjavax.servlet.http.HttpServletRequest;
  7. importjavax.servlet.http.HttpServletResponse;
  8. importnet.sf.json.JSONArray;
  9. importorg.springframework.stereotype.Controller;
  10. importorg.springframework.web.bind.annotation.PathVariable;
  11. importorg.springframework.web.bind.annotation.RequestMapping;
  12. importorg.springframework.web.bind.annotation.RequestMethod;
  13. importorg.springframework.web.bind.annotation.RequestParam;
  14. @Controller
  15. @RequestMapping(value="/getData")
  16. publicclassRestFul{
  17. //http://localhost:8080/RestWebService/getData?userName=sun方式的调用
  18. @RequestMapping
  19. publicvoidprintData1(HttpServletRequestrequest,HttpServletResponseresponse,
  20. @RequestParam(value="userName",defaultValue="User")Stringname){
  21. Stringmsg="Welcome"+name;
  22. printData(response,msg);
  23. }
  24. //http://localhost:8080/RestWebService/getData/Sun/Royi方式的调用
  25. @RequestMapping(value="/{firstName}/{lastName}")
  26. publicvoidprintData2(HttpServletRequestrequest,HttpServletResponseresponse,
  27. @PathVariableStringfirstName,@PathVariableStringlastName){
  28. Stringmsg="Welcome"+firstName+""+lastName;
  29. printData(response,msg);
  30. }
  31. //转换成HTML形式返回
  32. privatevoidprintData(HttpServletResponseresponse,Stringmsg){
  33. try{
  34. response.setContentType("text/html;charset=utf-8");
  35. response.setCharacterEncoding("UTF-8");
  36. PrintWriterout=newPrintWriter(newOutputStreamWriter(response.getOutputStream(),"UTF-8"));
  37. out.println(msg);
  38. out.close();
  39. }catch(Exceptione){
  40. e.printStackTrace();
  41. }
  42. }
  43. //http://localhost:8080/RestWebService/getData/json?item=0方式的调用
  44. @RequestMapping(value="/json")
  45. publicvoidprintData3(HttpServletRequestrequest,HttpServletResponseresponse,
  46. @RequestParam(value="item",defaultValue="0")Stringitem){
  47. printDataJason(response,item);
  48. }
  49. //http://localhost:8080/RestWebService/getData/json/1方式的调用
  50. @RequestMapping(value="/json/{item}")
  51. publicvoidprintData4(HttpServletRequestrequest,HttpServletResponseresponse,
  52. @PathVariableStringitem){
  53. printDataJason(response,item);
  54. }
  55. //JSON格式化
  56. privatevoidprintDataJason(HttpServletResponseresponse,Stringitem){
  57. try{
  58. response.setContentType("text/html;charset=utf-8");
  59. response.setCharacterEncoding("UTF-8");
  60. PrintWriterout=newPrintWriter(newOutputStreamWriter(response.getOutputStream(),"UTF-8"));
  61. List<UserInfo>uiList=newArrayList<UserInfo>();
  62. for(inti=0;i<3;i++)
  63. {
  64. UserInfoui=newUserInfo();
  65. ui.ID=i;
  66. ui.Name="SUN"+i;
  67. ui.Position="Position"+i;
  68. uiList.add(ui);
  69. if(!item.equals("0")){
  70. JSONArrayjsonArr=JSONArray.fromObject(uiList.get(0));
  71. out.println(jsonArr);
  72. }
  73. else{
  74. JSONArrayjsonArr=JSONArray.fromObject(uiList);
  75. out.println(jsonArr);
  76. //out.println(uiList);
  77. }
  78. out.close();
  79. }catch(Exceptione){
  80. e.printStackTrace();
  81. }
  82. }
  83. }


UserInfo.java

[java]view plaincopy
  1. packagecom.webservice;
  2. publicclassUserInfo{
  3. IntegerID;
  4. StringName;
  5. StringPosition;
  6. publicIntegergetID(){
  7. returnID;
  8. }
  9. publicvoidsetID(IntegeriD){
  10. ID=iD;
  11. }
  12. publicStringgetName(){
  13. returnName;
  14. }
  15. publicvoidsetName(Stringname){
  16. Name=name;
  17. }
  18. publicStringgetPosition(){
  19. returnPosition;
  20. }
  21. publicvoidsetPosition(Stringposition){
  22. Position=position;
  23. }
  24. }


3.SpringMVC框架需要修改一些配置:
web.xml

[html]view plaincopy
  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <web-appxmlns: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/javaeehttp://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 plaincopy
  1. springmvc-servlet.xml:
  2. <prename="code"><?xmlversion="1.0"encoding="UTF-8"?>
  3. <beansxmlns="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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  8. http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd
  9. http://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
  10. <context:annotation-config/>
  11. <mvc:default-servlet-handler/>
  12. <!--默认访问跳转到登录页面-->
  13. <mvc:view-controllerpath="/"view-name="redirect:/getData"/>
  14. <!--Scanstheclasspathofthisapplicationfor@Componentstodeployasbeans-->
  15. <context:component-scanbase-package="com.webservice">
  16. <context:include-filtertype="annotation"expression="org.springframework.stereotype.Controller"/>
  17. </context:component-scan>
  18. <!--采用SpringMVC自带的JSON转换工具,支持@ResponseBody注解-->
  19. <bean>
  20. <propertyname="messageConverters">
  21. <list>
  22. <refbean="stringHttpMessageConverter"/>
  23. <refbean="jsonHttpMessageConverter"/>
  24. </list>
  25. </property>
  26. </bean>
  27. <bean>
  28. <propertyname="supportedMediaTypes">
  29. <list>
  30. <value>text/plain;charset=UTF-8</value>
  31. </list>
  32. </property>
  33. </bean>
  34. <!--Configuresthe@Controllerprogrammingmodel-->
  35. <mvc:annotation-driven/>
  36. </beans>

rest-servlet.xml

[html]view plaincopy
  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <beans:beansxmlns="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/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd
  7. http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd">
  9. <!--EnablestheSpringMVC@Controllerprogrammingmodel-->
  10. <annotation-driven/>
  11. <!--forprocessingrequestswithannotatedcontrollermethodsandsetMessageConvertorsfromthelistofconvertors-->
  12. <beans:bean>
  13. <beans:propertyname="messageConverters">
  14. <beans:list>
  15. <beans:refbean="jsonMessageConverter"/>
  16. </beans:list>
  17. </beans:property>
  18. </beans:bean>
  19. <!--ToconvertJSONtoObjectandviceversa-->
  20. <beans:bean>
  21. </beans:bean>
  22. <context:component-scanbase-package="net.javaonline.spring.restful"/>
  23. </beans:beans>


4.用到的Jar包:

[plain]view plaincopy
  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 plaincopy
  1. packagecom.httpclientforrest;
  2. importjava.util.ArrayList;
  3. importjava.util.List;
  4. importorg.apache.http.HttpEntity;
  5. importorg.apache.http.NameValuePair;
  6. importorg.apache.http.client.entity.UrlEncodedFormEntity;
  7. importorg.apache.http.client.methods.CloseableHttpResponse;
  8. importorg.apache.http.client.methods.HttpPost;
  9. importorg.apache.http.impl.client.CloseableHttpClient;
  10. importorg.apache.http.impl.client.HttpClients;
  11. importorg.apache.http.message.BasicNameValuePair;
  12. importorg.apache.http.util.EntityUtils;
  13. publicclassRest{
  14. publicstaticvoidmain(String[]args){
  15. List<NameValuePair>params=newArrayList<NameValuePair>();
  16. params.add(newBasicNameValuePair("userName","Sun"));
  17. Stringurl="http://localhost:8080/RestWebService/getData";
  18. System.out.println(getRest(url,params));
  19. }
  20. publicstaticStringgetRest(Stringurl,List<NameValuePair>params){
  21. //创建默认的httpClient实例.
  22. CloseableHttpClienthttpclient=HttpClients.createDefault();
  23. //创建httppost
  24. HttpPosthttppost=newHttpPost(url);
  25. UrlEncodedFormEntityuefEntity;
  26. try{
  27. uefEntity=newUrlEncodedFormEntity(params,"UTF-8");
  28. httppost.setEntity(uefEntity);
  29. CloseableHttpResponseresponse=httpclient.execute(httppost);
  30. HttpEntityentity=response.getEntity();
  31. Stringjson=EntityUtils.toString(entity,"UTF-8");
  32. intcode=response.getStatusLine().getStatusCode();
  33. if(code==200||code==204){
  34. returnjson;
  35. }
  36. }catch(Exceptione){
  37. e.printStackTrace();
  38. }
  39. return"";
  40. }
  41. }


执行结果:

[plain]view plaincopy
  1. WelcomeSun
[html]view plaincopy
  1. 方法2:在JSP页面用JQuery调用:
  2. 1.创建【DynamicWebPrject】
  3. 相关配置文件和创建RestFulWebService相同。
  4. 2.建一个JSP页面:
  5. rest.jsp:
  6. <prename="code"><%@pagelanguage="java"import="java.util.*"pageEncoding="ISO-8859-1"%>
  7. <%
  8. Stringpath=request.getContextPath();
  9. StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  10. %>
  11. <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
  12. <html>
  13. <head>
  14. <basehref="<%=basePath%>">
  15. <title>RestfilWebService</title>
  16. <metahttp-equiv="pragma"content="no-cache">
我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved