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

时间:2023-03-09 21:04:39
SpringMVC+Json构建基于Restful风格的应用(转)

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

二、所需其它Jar包:

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

三、主要代码:

web.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  4. version="2.5">
  5. <context-param>
  6. <param-name>log4jConfigLocation</param-name>
  7. <param-value>classpath:log4j.properties</param-value>
  8. </context-param>
  9. <context-param>
  10. <param-name>log4jRefreshInterval</param-name>
  11. <param-value>60000</param-value>
  12. </context-param>
  13. <context-param>
  14. <param-name>contextConfigLocation</param-name>
  15. <param-value>classpath:applicationContext.xml</param-value>
  16. </context-param>
  17. <!-- 编码过虑 -->
  18. <filter>
  19. <filter-name>encodingFilter</filter-name>
  20. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  21. <init-param>
  22. <param-name>encoding</param-name>
  23. <param-value>UTF-8</param-value>
  24. </init-param>
  25. <init-param>
  26. <param-name>forceEncoding</param-name>
  27. <param-value>true</param-value>
  28. </init-param>
  29. </filter>
  30. <filter-mapping>
  31. <filter-name>encodingFilter</filter-name>
  32. <url-pattern>/*</url-pattern>
  33. </filter-mapping>
  34. <!-- Spring监听 -->
  35. <listener>
  36. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  37. </listener>
  38. <!-- Spring MVC DispatcherServlet -->
  39. <servlet>
  40. <servlet-name>springMVC3</servlet-name>
  41. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  42. <init-param>
  43. <param-name>contextConfigLocation</param-name>
  44. <param-value>classpath:springMVC-servlet.xml</param-value>
  45. </init-param>
  46. <load-on-startup>1</load-on-startup>
  47. </servlet>
  48. <servlet-mapping>
  49. <servlet-name>springMVC3</servlet-name>
  50. <url-pattern>/</url-pattern>
  51. </servlet-mapping>
  52. <!-- 解决HTTP PUT请求Spring无法获取请求参数的问题 -->
  53. <filter>
  54. <filter-name>HiddenHttpMethodFilter</filter-name>
  55. <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  56. </filter>
  57. <filter-mapping>
  58. <filter-name>HiddenHttpMethodFilter</filter-name>
  59. <servlet-name>springMVC3</servlet-name>
  60. </filter-mapping>
  61. <display-name>UikitTest</display-name>
  62. <welcome-file-list>
  63. <welcome-file>/WEB-INF/jsp/index.jsp</welcome-file>
  64. </welcome-file-list>
  65. </web-app>

springMVC-servlet.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans default-lazy-init="true"
  3. xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
  5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
  6. xmlns:mvc="http://www.springframework.org/schema/mvc"
  7. xsi:schemaLocation="
  8. http://www.springframework.org/schema/beans
  9. http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
  10. http://www.springframework.org/schema/mvc
  11. http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
  12. http://www.springframework.org/schema/context
  13. http://www.springframework.org/schema/context/spring-context-3.1.xsd">
  14. <!-- 注解驱动 -->
  15. <mvc:annotation-driven />
  16. <!-- 扫描包 -->
  17. <context:component-scan base-package="com.citic.test.action" />
  18. <!-- 用于页面跳转,根据请求的不同跳转到不同页面,如请求index.do则跳转到/WEB-INF/jsp/index.jsp -->
  19. <bean id="findJsp"
  20. class="org.springframework.web.servlet.mvc.UrlFilenameViewController" />
  21. <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
  22. <property name="mappings">
  23. <props>
  24. <prop key="index.do">findJsp</prop><!-- 表示index.do转向index.jsp页面 -->
  25. <prop key="first.do">findJsp</prop><!-- 表示first.do转向first.jsp页面 -->
  26. </props>
  27. </property>
  28. </bean>
  29. <!-- 视图解析 -->
  30. <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
  31. <!-- 返回的视图模型数据需要经过jstl来处理 -->
  32. <property name="viewClass"
  33. value="org.springframework.web.servlet.view.JstlView" />
  34. <property name="prefix" value="/WEB-INF/jsp/" />
  35. <property name="suffix" value=".jsp" />
  36. </bean>
  37. <!-- 对静态资源文件的访问 不支持访问WEB-INF目录 -->
  38. <mvc:default-servlet-handler />
  39. <!-- 对静态资源文件的访问 支持访问WEB-INF目录 -->
  40. <!-- <mvc:resources location="/uikit-2.3.1/" mapping="/uikit-2.3.1/**" /> -->
  41. <bean id="stringConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
  42. <property name="supportedMediaTypes">
  43. <list>
  44. <value>text/plain;charset=UTF-8</value>
  45. </list>
  46. </property>
  47. </bean>
  48. <!-- 输出对象转JSON支持 -->
  49. <bean id="jsonConverter"
  50. class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
  51. <bean
  52. class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  53. <property name="messageConverters">
  54. <list>
  55. <ref bean="stringConverter"/>
  56. <ref bean="jsonConverter" />
  57. </list>
  58. </property>
  59. </bean>
  60. </beans>

Controller:

  1. package com.citic.test.action;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import net.sf.json.JSONObject;
  5. import org.apache.log4j.Logger;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.web.bind.annotation.PathVariable;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RequestMethod;
  10. import org.springframework.web.bind.annotation.RequestParam;
  11. import org.springframework.web.bind.annotation.ResponseBody;
  12. import com.citic.test.entity.Person;
  13. /**
  14. * 基于Restful风格架构测试
  15. *
  16. * @author dekota
  17. * @since JDK1.5
  18. * @version V1.0
  19. * @history 2014-2-15 下午3:00:12 dekota 新建
  20. */
  21. @Controller
  22. public class DekotaAction {
  23. /** 日志实例 */
  24. private static final Logger logger = Logger.getLogger(DekotaAction.class);
  25. @RequestMapping(value = "/hello", produces = "text/plain;charset=UTF-8")
  26. public @ResponseBody
  27. String hello() {
  28. return "你好!hello";
  29. }
  30. @RequestMapping(value = "/say/{msg}", produces = "application/json;charset=UTF-8")
  31. public @ResponseBody
  32. String say(@PathVariable(value = "msg") String msg) {
  33. return "{\"msg\":\"you say:'" + msg + "'\"}";
  34. }
  35. @RequestMapping(value = "/person/{id:\\d+}", method = RequestMethod.GET)
  36. public @ResponseBody
  37. Person getPerson(@PathVariable("id") int id) {
  38. logger.info("获取人员信息id=" + id);
  39. Person person = new Person();
  40. person.setName("张三");
  41. person.setSex("男");
  42. person.setAge(30);
  43. person.setId(id);
  44. return person;
  45. }
  46. @RequestMapping(value = "/person/{id:\\d+}", method = RequestMethod.DELETE)
  47. public @ResponseBody
  48. Object deletePerson(@PathVariable("id") int id) {
  49. logger.info("删除人员信息id=" + id);
  50. JSONObject jsonObject = new JSONObject();
  51. jsonObject.put("msg", "删除人员信息成功");
  52. return jsonObject;
  53. }
  54. @RequestMapping(value = "/person", method = RequestMethod.POST)
  55. public @ResponseBody
  56. Object addPerson(Person person) {
  57. logger.info("注册人员信息成功id=" + person.getId());
  58. JSONObject jsonObject = new JSONObject();
  59. jsonObject.put("msg", "注册人员信息成功");
  60. return jsonObject;
  61. }
  62. @RequestMapping(value = "/person", method = RequestMethod.PUT)
  63. public @ResponseBody
  64. Object updatePerson(Person person) {
  65. logger.info("更新人员信息id=" + person.getId());
  66. JSONObject jsonObject = new JSONObject();
  67. jsonObject.put("msg", "更新人员信息成功");
  68. return jsonObject;
  69. }
  70. @RequestMapping(value = "/person", method = RequestMethod.PATCH)
  71. public @ResponseBody
  72. List<Person> listPerson(@RequestParam(value = "name", required = false, defaultValue = "") String name) {
  73. logger.info("查询人员name like " + name);
  74. List<Person> lstPersons = new ArrayList<Person>();
  75. Person person = new Person();
  76. person.setName("张三");
  77. person.setSex("男");
  78. person.setAge(25);
  79. person.setId(101);
  80. lstPersons.add(person);
  81. Person person2 = new Person();
  82. person2.setName("李四");
  83. person2.setSex("女");
  84. person2.setAge(23);
  85. person2.setId(102);
  86. lstPersons.add(person2);
  87. Person person3 = new Person();
  88. person3.setName("王五");
  89. person3.setSex("男");
  90. person3.setAge(27);
  91. person3.setId(103);
  92. lstPersons.add(person3);
  93. return lstPersons;
  94. }
  95. }

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

部分调试效果:

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

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

http://blog.csdn.net/greensurfer/article/details/19296247