SpringMVC+Json构建基于Restful风格的应用

一、spring 版本:spring-framework-3.2.7.RELEASE

二、所需其它Jar包:

SpringMVC+Json构建基于Restful风格的应用

三、主要代码:

web.xml

<?xml version="1.0" encoding="UTF-8"?>  
<web-app xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
    version="2.5">  
  
    <context-param>  
        <param-name>log4jConfigLocation</param-name>  
        <param-value>classpath:log4j.properties</param-value>  
    </context-param>  
    <context-param>  
        <param-name>log4jRefreshInterval</param-name>  
        <param-value>60000</param-value>  
    </context-param>  
    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath:applicationContext.xml</param-value>  
    </context-param>  
  
    <!-- 编码过虑 -->  
    <filter>  
        <filter-name>encodingFilter</filter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
        <init-param>  
            <param-name>encoding</param-name>  
            <param-value>UTF-8</param-value>  
        </init-param>  
        <init-param>  
            <param-name>forceEncoding</param-name>  
            <param-value>true</param-value>  
        </init-param>  
    </filter>  
    <filter-mapping>  
        <filter-name>encodingFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  
  
    <!-- Spring监听 -->  
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener>  
  
    <!-- Spring MVC DispatcherServlet -->  
    <servlet>  
        <servlet-name>springMVC3</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <init-param>  
            <param-name>contextConfigLocation</param-name>  
            <param-value>classpath:springMVC-servlet.xml</param-value>  
        </init-param>  
        <load-on-startup>1</load-on-startup>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>springMVC3</servlet-name>  
        <url-pattern>/</url-pattern>  
    </servlet-mapping>  
  
    <!-- 解决HTTP PUT请求Spring无法获取请求参数的问题 -->  
    <filter>  
        <filter-name>HiddenHttpMethodFilter</filter-name>  
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>  
    </filter>  
    <filter-mapping>  
        <filter-name>HiddenHttpMethodFilter</filter-name>  
        <servlet-name>springMVC3</servlet-name>  
    </filter-mapping>  
  
  
    <display-name>UikitTest</display-name>  
    <welcome-file-list>  
        <welcome-file>/WEB-INF/jsp/index.jsp</welcome-file>  
    </welcome-file-list>  
  
</web-app>  


springMVC-servlet.xml

package com.citic.test.action;  
  
import java.util.ArrayList;  
import java.util.List;  
  
import net.sf.json.JSONObject;  
  
import org.apache.log4j.Logger;  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;  
import org.springframework.web.bind.annotation.RequestParam;  
import org.springframework.web.bind.annotation.ResponseBody;  
  
import com.citic.test.entity.Person;  
  
/** 
 * 基于Restful风格架构测试 
 *  
 * @author dekota 
 * @since JDK1.5 
 * @version V1.0 
 * @history 2014-2-15 下午3:00:12 dekota 新建 
 */  
@Controller  
public class DekotaAction {  
  
    /** 日志实例 */  
    private static final Logger logger = Logger.getLogger(DekotaAction.class);  
  
    @RequestMapping(value = "/hello", produces = "text/plain;charset=UTF-8")  
    public @ResponseBody  
    String hello() {  
        return "你好!hello";  
    }  
  
    @RequestMapping(value = "/say/{msg}", produces = "application/json;charset=UTF-8")  
    public @ResponseBody  
    String say(@PathVariable(value = "msg") String msg) {  
        return "{\"msg\":\"you say:'" + msg + "'\"}";  
    }  
  
    @RequestMapping(value = "/person/{id:\\d+}", method = RequestMethod.GET)  
    public @ResponseBody  
    Person getPerson(@PathVariable("id") int id) {  
        logger.info("获取人员信息id=" + id);  
        Person person = new Person();  
        person.setName("张三");  
        person.setSex("男");  
        person.setAge(30);  
        person.setId(id);  
        return person;  
    }  
  
    @RequestMapping(value = "/person/{id:\\d+}", method = RequestMethod.DELETE)  
    public @ResponseBody  
    Object deletePerson(@PathVariable("id") int id) {  
        logger.info("删除人员信息id=" + id);  
        JSONObject jsonObject = new JSONObject();  
        jsonObject.put("msg", "删除人员信息成功");  
        return jsonObject;  
    }  
  
    @RequestMapping(value = "/person", method = RequestMethod.POST)  
    public @ResponseBody  
    Object addPerson(Person person) {  
        logger.info("注册人员信息成功id=" + person.getId());  
        JSONObject jsonObject = new JSONObject();  
        jsonObject.put("msg", "注册人员信息成功");  
        return jsonObject;  
    }  
  
    @RequestMapping(value = "/person", method = RequestMethod.PUT)  
    public @ResponseBody  
    Object updatePerson(Person person) {  
        logger.info("更新人员信息id=" + person.getId());  
        JSONObject jsonObject = new JSONObject();  
        jsonObject.put("msg", "更新人员信息成功");  
        return jsonObject;  
    }  
  
    @RequestMapping(value = "/person", method = RequestMethod.PATCH)  
    public @ResponseBody  List<Person> 
       listPerson(@RequestParam(value = "name", required = false, defaultValue = "") String name) {  
  
        logger.info("查询人员name like " + name);  
        List<Person> lstPersons = new ArrayList<Person>();  
  
        Person person = new Person();  
        person.setName("张三");  
        person.setSex("男");  
        person.setAge(25);  
        person.setId(101);  
        lstPersons.add(person);  
  
        Person person2 = new Person();  
        person2.setName("李四");  
        person2.setSex("女");  
        person2.setAge(23);  
        person2.setId(102);  
        lstPersons.add(person2);  
  
        Person person3 = new Person();  
        person3.setName("王五");  
        person3.setSex("男");  
        person3.setAge(27);  
        person3.setId(103);  
        lstPersons.add(person3);  
  
        return lstPersons;  
    }  
  
}  

index.jsp

  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3.     String path = request.getContextPath();  
  4.     String basePath = request.getScheme() + "://"  
  5.             + request.getServerName() + ":" + request.getServerPort()  
  6.             + path + "/";  
  7. %>  
  8.   
  9. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  10. <html>  
  11. <head>  
  12. <base href="<%=basePath%>">  
  13.   
  14. <title>Uikit Test</title>  
  15.     <meta http-equiv="pragma" content="no-cache">  
  16.     <meta http-equiv="cache-control" content="no-cache">  
  17.     <meta http-equiv="expires" content="0">  
  18.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  19.     <meta http-equiv="description" content="This is my page">  
  20.     <link rel="stylesheet" type="text/css"   href="uikit-2.3.1/css/uikit.gradient.min.css">  
  21.     <link rel="stylesheet" type="text/css" href="uikit-2.3.1/addons/css/notify.gradient.min.css">  
  22. </head>  
  23. <body>  
  24. <div  
  25.     style="width:800px;margin-top:10px;margin-left: auto;margin-right: auto;text-align: center;">  
  26.     <h2>Uikit Test</h2>  
  27. </div>  
  28. <div style="width:800px;margin-left: auto;margin-right: auto;">  
  29.     <fieldset class="uk-form">  
  30.         <legend>Uikit表单渲染测试</legend>  
  31.         <div class="uk-form-row">  
  32.             <input type="text" class="uk-width-1-1">  
  33.         </div>  
  34.         <div class="uk-form-row">  
  35.             <input type="text" class="uk-width-1-1 uk-form-success">  
  36.         </div>  
  37.         <div class="uk-form-row">  
  38.             <input type="text" class="uk-width-1-1 uk-form-danger">  
  39.         </div>  
  40.         <div class="uk-form-row">  
  41.             <input type="text" class="uk-width-1-1">  
  42.         </div>  
  43.         <div class="uk-form-row">  
  44.             <select id="form-s-s">  
  45.                 <option>---请选择---</option>  
  46.                 <option>是</option>  
  47.                 <option>否</option>  
  48.             </select>  
  49.         </div>  
  50.         <div class="uk-form-row">  
  51.             <input type="date" id="form-h-id" />  
  52.         </div>  
  53.     </fieldset>  
  54.     <fieldset class="uk-form">  
  55.         <legend>基于Restful架构风格的资源请求测试</legend>  
  56.         <button class="uk-button uk-button-primary uk-button-large" id="btnGet">获取人员GET</button>  
  57.         <button class="uk-button uk-button-primary uk-button-large" id="btnAdd">添加人员POST</button>  
  58.         <button class="uk-button uk-button-primary uk-button-large" id="btnUpdate">更新人员PUT</button>  
  59.         <button class="uk-button uk-button-danger uk-button-large" id="btnDel">删除人员DELETE</button>  
  60.         <button class="uk-button uk-button-primary uk-button-large" id="btnList">查询列表PATCH</button>  
  61.     </fieldset>  
  62. </div>  
  63.   
  64. <script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>  
  65. <script type="text/javascript" src="uikit-2.3.1/js/uikit.min.js"></script>  
  66. <script type="text/javascript" src="uikit-2.3.1/addons/js/notify.min.js"></script>  
  67. <script type="text/javascript">  
  68.     (function(window,$){  
  69.   
  70.         var dekota={  
  71.               
  72.             url:'',  
  73.   
  74.             init:function(){  
  75.                 dekota.url='<%=basePath%>';  
  76.                 $.UIkit.notify("页面初始化完成", {status:'info',timeout:500});  
  77.                 $("#btnGet").click(dekota.getPerson);  
  78.                 $("#btnAdd").click(dekota.addPerson);  
  79.                 $("#btnDel").click(dekota.delPerson);  
  80.                 $("#btnUpdate").click(dekota.updatePerson);  
  81.                 $("#btnList").click(dekota.listPerson);  
  82.             },  
  83.             getPerson:function(){  
  84.                 $.ajax({  
  85.                     url: dekota.url + 'person/101/',  
  86.                     type: 'GET',  
  87.                     dataType: 'json'  
  88.                 }).done(function(data, status, xhr) {  
  89.                     $.UIkit.notify("获取人员信息成功", {status:'success',timeout:1000});  
  90.                 }).fail(function(xhr, status, error) {  
  91.                     $.UIkit.notify("请求失败!", {status:'danger',timeout:2000});  
  92.                 });  
  93.             },  
  94.             addPerson:function(){  
  95.                 $.ajax({  
  96.                     url: dekota.url + 'person',  
  97.                     type: 'POST',  
  98.                     dataType: 'json',  
  99.                     data: {id: 1,name:'张三',sex:'男',age:23}  
  100.                 }).done(function(data, status, xhr) {  
  101.                     $.UIkit.notify(data.msg, {status:'success',timeout:1000});  
  102.                 }).fail(function(xhr, status, error) {  
  103.                     $.UIkit.notify("请求失败!", {status:'danger',timeout:2000});  
  104.                 });  
  105.             },  
  106.             delPerson:function(){  
  107.                 $.ajax({  
  108.                     url: dekota.url + 'person/109',  
  109.                     type: 'DELETE',  
  110.                     dataType: 'json'  
  111.                 }).done(function(data, status, xhr) {  
  112.                     $.UIkit.notify(data.msg, {status:'success',timeout:1000});  
  113.                 }).fail(function(xhr, status, error) {  
  114.                     $.UIkit.notify("请求失败!", {status:'danger',timeout:2000});  
  115.                 });  
  116.             },  
  117.             updatePerson:function(){  
  118.                 $.ajax({  
  119.                     url: dekota.url + 'person',  
  120.                     type: 'POST',//注意在传参数时,加:_method:'PUT' 将对应后台的PUT请求方法  
  121.                     dataType: 'json',  
  122.                     data: {_method:'PUT',id: 221,name:'王五',sex:'男',age:23}  
  123.                 }).done(function(data, status, xhr) {  
  124.                     $.UIkit.notify(data.msg, {status:'success',timeout:1000});  
  125.                 }).fail(function(xhr, status, error) {  
  126.                     $.UIkit.notify("请求失败!", {status:'danger',timeout:2000});  
  127.                 });  
  128.             },  
  129.             listPerson:function(){  
  130.                 $.ajax({  
  131.                     url: dekota.url + 'person',  
  132.                     type: 'POST',//注意在传参数时,加:_method:'PATCH' 将对应后台的PATCH请求方法  
  133.                     dataType: 'json',  
  134.                     data: {_method:'PATCH',name: '张三'}  
  135.                 }).done(function(data, status, xhr) {  
  136.                     $.UIkit.notify("查询人员信息成功", {status:'success',timeout:1000});  
  137.                 }).fail(function(xhr, status, error) {  
  138.                     $.UIkit.notify("请求失败!", {status:'danger',timeout:2000});  
  139.                 });  
  140.             }  
  141.         };  
  142.         window.dekota=(window.dekota)?window.dekota:dekota;  
  143.         $(function(){  
  144.             dekota.init();  
  145.         });  
  146.     })(window,jQuery);  
  147.   
  148. </script>  
  149. </body>  
  150. </html>  

部分调试效果:

SpringMVC+Json构建基于Restful风格的应用

SpringMVC+Json构建基于Restful风格的应用

相关推荐