牛骨文教育服务平台(让学习变的简单)
博文笔记

RestFul WebService的创建和使用实例

创建时间:2017-02-16 投稿人: 浏览次数:1800
一. 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.            &n
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。