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

二、所需其它Jar包:

三、主要代码:

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>

部分调试效果:

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

SpringMVC+Json构建基于Restful风格的应用(转)的更多相关文章

  1. springMVC+json构建restful风格的服务

    首先.要知道什么是rest服务,什么是rest服务呢? REST(英文:Representational State Transfer,简称REST)描写叙述了一个架构样式的网络系统.比方 web 应 ...

  2. MockMVC - 基于RESTful风格的Springboot,SpringMVC的测试

    MockMVC - 基于RESTful风格的SpringMVC的测试 对于前后端分离的项目而言,无法直接从前端静态代码中测试接口的正确性,因此可以通过MockMVC来模拟HTTP请求.基于RESTfu ...

  3. ASP.NET WEB API构建基于REST风格

    使用ASP.NET WEB API构建基于REST风格的服务实战系列教程[开篇] 最近发现web api很火,园内也有各种大神已经在研究,本人在asp.net官网上看到一个系列教程,原文地址:http ...

  4. ASP.NET Web Api构建基于REST风格的服务实战系列教程

    使用ASP.NET Web Api构建基于REST风格的服务实战系列教程[十]——使用CacheCow和ETag缓存资源 系列导航地址http://www.cnblogs.com/fzrain/p/3 ...

  5. 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程【开篇】【持续更新中。。。】

    最近发现web api很火,园内也有各种大神已经在研究,本人在asp.net官网上看到一个系列教程,原文地址:http://bitoftech.net/2013/11/25/detailed-tuto ...

  6. SpringMVC(三)Restful风格及实例、参数的转换

    个人博客网:https://wushaopei.github.io/    (你想要这里多有) 一.Restful风格 1.Restful风格的介绍 Restful 一种软件架构风格.设计风格,而不是 ...

  7. SpringMVC学习笔记之---RESTful风格

    RESTful风格 (一)什么是RESTful (1)RESTful不是一套标准,只是一套开发方式,构架思想 (2)url更加简洁 (3)有利于不同系统之间的资源共享 (二)概述 RESTful具体来 ...

  8. springMVC入门(六)------json交互与RESTFul风格支持

    简介 JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.由于其简单易用,目前常用来通过AJAX与后台进行交互.springMVC对于接收.发送JSON数据也 ...

  9. 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程【三】——Web Api入门

    系列导航地址http://www.cnblogs.com/fzrain/p/3490137.html 前言 经过前2节的介绍,我们已经把数据访问层搭建好了,从本章开始就是Web Api部分了.在正式开 ...

随机推荐

  1. 一个类搞定UIScrollView那些事

    前言 UIScrollView可以说是我们在日常编程中使用频率最多.扩展性最好的一个类,根据不同的需求和设计,我们都能玩出花来,当然有一些需求是大部分应用通用的,今天就聊一下以下需求,在一个categ ...

  2. C++中各种数据量类型转换

    要在Unicode字符集环境下把CString转化为char* 方法: CString str = _T("D://校内项目//QQ.bmp");//////leo这个NB  可以 ...

  3. 科讯CMS V9标签清单

    全新整理V9标签清单 ====================网站通用标签============== {$GetSiteTitle} 显示网站标题 {$GetSiteName} 显示网站名称 {$G ...

  4. SAMBA用户访问指定的目录

    指定某个用户访问一个特定的共享文件夹sfx 用户可以访问abc目录 别的用户不可以访问abc目录 先创建一个用户命令useradd sfx 创建一个smbpasswd用户 在创建这个用户时要先创建一个 ...

  5. play app to war

    project/Build.scala import sbt._ import Keys._ import play.Play.autoImport._ import PlayKeys._ impor ...

  6. How to hanganalyze and systemstate dumps

    Oracle support request hang analysis and system state dumps when rasing SR. One 10.1 or higher versi ...

  7. oracle 权限管理

    系统权限 系统权限需要授予者有进行系统级活动的能力,如连接数据库,更改用户会话.建立表或建立用户等等.你可以在数据字典视图SYSTEM_PRIVILEGE_MAP上获得完整的系统权限.对象权限和系统权 ...

  8. C# 进程 和线程

    进程 没有应用程序可以看做是一个进程 线程:就是对cpu执行的最小单位 单线程:前台线程和后台线程 带来的问题:假死 net中不能跨线程访问

  9. PHP 学习笔记 (二)

    PHP中的错误级别: PHP中的报错有3中级别: NOTICE.WARNING.ERROR. NOTICE是级别最轻的一种,一般表示代码不规范,但是程序是可以正常运行的 Warning是比NOTICE ...

  10. 在Windows下用MingW 4.5.2编译OpenCV 2.3.0

    需要的工具:1.安装QT SDK环境2.安装CMake for Windows3.OpenCV最新Windows源码步骤:1.将QT SDK安装目录下的{QtSDK}\mingw\bin添加到系统环境 ...