SpringMVC+Json构建基于Restful风格的应用(转)
一、spring 版本:spring-framework-3.2.7.RELEASE
二、所需其它Jar包:
三、主要代码:
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
- <?xml version="1.0" encoding="UTF-8"?>
- <beans default-lazy-init="true"
- xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p"
- xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.1.xsd">
- <!-- 注解驱动 -->
- <mvc:annotation-driven />
- <!-- 扫描包 -->
- <context:component-scan base-package="com.citic.test.action" />
- <!-- 用于页面跳转,根据请求的不同跳转到不同页面,如请求index.do则跳转到/WEB-INF/jsp/index.jsp -->
- <bean id="findJsp"
- class="org.springframework.web.servlet.mvc.UrlFilenameViewController" />
- <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
- <property name="mappings">
- <props>
- <prop key="index.do">findJsp</prop><!-- 表示index.do转向index.jsp页面 -->
- <prop key="first.do">findJsp</prop><!-- 表示first.do转向first.jsp页面 -->
- </props>
- </property>
- </bean>
- <!-- 视图解析 -->
- <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
- <!-- 返回的视图模型数据需要经过jstl来处理 -->
- <property name="viewClass"
- value="org.springframework.web.servlet.view.JstlView" />
- <property name="prefix" value="/WEB-INF/jsp/" />
- <property name="suffix" value=".jsp" />
- </bean>
- <!-- 对静态资源文件的访问 不支持访问WEB-INF目录 -->
- <mvc:default-servlet-handler />
- <!-- 对静态资源文件的访问 支持访问WEB-INF目录 -->
- <!-- <mvc:resources location="/uikit-2.3.1/" mapping="/uikit-2.3.1/**" /> -->
- <bean id="stringConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
- <property name="supportedMediaTypes">
- <list>
- <value>text/plain;charset=UTF-8</value>
- </list>
- </property>
- </bean>
- <!-- 输出对象转JSON支持 -->
- <bean id="jsonConverter"
- class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
- <bean
- class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
- <property name="messageConverters">
- <list>
- <ref bean="stringConverter"/>
- <ref bean="jsonConverter" />
- </list>
- </property>
- </bean>
- </beans>
Controller:
- 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
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme() + "://"
- + request.getServerName() + ":" + request.getServerPort()
- + path + "/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>Uikit Test</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <link rel="stylesheet" type="text/css" href="uikit-2.3.1/css/uikit.gradient.min.css">
- <link rel="stylesheet" type="text/css" href="uikit-2.3.1/addons/css/notify.gradient.min.css">
- </head>
- <body>
- <div
- style="width:800px;margin-top:10px;margin-left: auto;margin-right: auto;text-align: center;">
- <h2>Uikit Test</h2>
- </div>
- <div style="width:800px;margin-left: auto;margin-right: auto;">
- <fieldset class="uk-form">
- <legend>Uikit表单渲染测试</legend>
- <div class="uk-form-row">
- <input type="text" class="uk-width-1-1">
- </div>
- <div class="uk-form-row">
- <input type="text" class="uk-width-1-1 uk-form-success">
- </div>
- <div class="uk-form-row">
- <input type="text" class="uk-width-1-1 uk-form-danger">
- </div>
- <div class="uk-form-row">
- <input type="text" class="uk-width-1-1">
- </div>
- <div class="uk-form-row">
- <select id="form-s-s">
- <option>---请选择---</option>
- <option>是</option>
- <option>否</option>
- </select>
- </div>
- <div class="uk-form-row">
- <input type="date" id="form-h-id" />
- </div>
- </fieldset>
- <fieldset class="uk-form">
- <legend>基于Restful架构风格的资源请求测试</legend>
- <button class="uk-button uk-button-primary uk-button-large" id="btnGet">获取人员GET</button>
- <button class="uk-button uk-button-primary uk-button-large" id="btnAdd">添加人员POST</button>
- <button class="uk-button uk-button-primary uk-button-large" id="btnUpdate">更新人员PUT</button>
- <button class="uk-button uk-button-danger uk-button-large" id="btnDel">删除人员DELETE</button>
- <button class="uk-button uk-button-primary uk-button-large" id="btnList">查询列表PATCH</button>
- </fieldset>
- </div>
- <script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
- <script type="text/javascript" src="uikit-2.3.1/js/uikit.min.js"></script>
- <script type="text/javascript" src="uikit-2.3.1/addons/js/notify.min.js"></script>
- <script type="text/javascript">
- (function(window,$){
- var dekota={
- url:'',
- init:function(){
- dekota.url='<%=basePath%>';
- $.UIkit.notify("页面初始化完成", {status:'info',timeout:500});
- $("#btnGet").click(dekota.getPerson);
- $("#btnAdd").click(dekota.addPerson);
- $("#btnDel").click(dekota.delPerson);
- $("#btnUpdate").click(dekota.updatePerson);
- $("#btnList").click(dekota.listPerson);
- },
- getPerson:function(){
- $.ajax({
- url: dekota.url + 'person/101/',
- type: 'GET',
- dataType: 'json'
- }).done(function(data, status, xhr) {
- $.UIkit.notify("获取人员信息成功", {status:'success',timeout:1000});
- }).fail(function(xhr, status, error) {
- $.UIkit.notify("请求失败!", {status:'danger',timeout:2000});
- });
- },
- addPerson:function(){
- $.ajax({
- url: dekota.url + 'person',
- type: 'POST',
- dataType: 'json',
- data: {id: 1,name:'张三',sex:'男',age:23}
- }).done(function(data, status, xhr) {
- $.UIkit.notify(data.msg, {status:'success',timeout:1000});
- }).fail(function(xhr, status, error) {
- $.UIkit.notify("请求失败!", {status:'danger',timeout:2000});
- });
- },
- delPerson:function(){
- $.ajax({
- url: dekota.url + 'person/109',
- type: 'DELETE',
- dataType: 'json'
- }).done(function(data, status, xhr) {
- $.UIkit.notify(data.msg, {status:'success',timeout:1000});
- }).fail(function(xhr, status, error) {
- $.UIkit.notify("请求失败!", {status:'danger',timeout:2000});
- });
- },
- updatePerson:function(){
- $.ajax({
- url: dekota.url + 'person',
- type: 'POST',//注意在传参数时,加:_method:'PUT' 将对应后台的PUT请求方法
- dataType: 'json',
- data: {_method:'PUT',id: 221,name:'王五',sex:'男',age:23}
- }).done(function(data, status, xhr) {
- $.UIkit.notify(data.msg, {status:'success',timeout:1000});
- }).fail(function(xhr, status, error) {
- $.UIkit.notify("请求失败!", {status:'danger',timeout:2000});
- });
- },
- listPerson:function(){
- $.ajax({
- url: dekota.url + 'person',
- type: 'POST',//注意在传参数时,加:_method:'PATCH' 将对应后台的PATCH请求方法
- dataType: 'json',
- data: {_method:'PATCH',name: '张三'}
- }).done(function(data, status, xhr) {
- $.UIkit.notify("查询人员信息成功", {status:'success',timeout:1000});
- }).fail(function(xhr, status, error) {
- $.UIkit.notify("请求失败!", {status:'danger',timeout:2000});
- });
- }
- };
- window.dekota=(window.dekota)?window.dekota:dekota;
- $(function(){
- dekota.init();
- });
- })(window,jQuery);
- </script>
- </body>
- </html>
部分调试效果:
http://blog.csdn.net/greensurfer/article/details/19296247
SpringMVC+Json构建基于Restful风格的应用(转)的更多相关文章
- springMVC+json构建restful风格的服务
首先.要知道什么是rest服务,什么是rest服务呢? REST(英文:Representational State Transfer,简称REST)描写叙述了一个架构样式的网络系统.比方 web 应 ...
- MockMVC - 基于RESTful风格的Springboot,SpringMVC的测试
MockMVC - 基于RESTful风格的SpringMVC的测试 对于前后端分离的项目而言,无法直接从前端静态代码中测试接口的正确性,因此可以通过MockMVC来模拟HTTP请求.基于RESTfu ...
- ASP.NET WEB API构建基于REST风格
使用ASP.NET WEB API构建基于REST风格的服务实战系列教程[开篇] 最近发现web api很火,园内也有各种大神已经在研究,本人在asp.net官网上看到一个系列教程,原文地址:http ...
- ASP.NET Web Api构建基于REST风格的服务实战系列教程
使用ASP.NET Web Api构建基于REST风格的服务实战系列教程[十]——使用CacheCow和ETag缓存资源 系列导航地址http://www.cnblogs.com/fzrain/p/3 ...
- 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程【开篇】【持续更新中。。。】
最近发现web api很火,园内也有各种大神已经在研究,本人在asp.net官网上看到一个系列教程,原文地址:http://bitoftech.net/2013/11/25/detailed-tuto ...
- SpringMVC(三)Restful风格及实例、参数的转换
个人博客网:https://wushaopei.github.io/ (你想要这里多有) 一.Restful风格 1.Restful风格的介绍 Restful 一种软件架构风格.设计风格,而不是 ...
- SpringMVC学习笔记之---RESTful风格
RESTful风格 (一)什么是RESTful (1)RESTful不是一套标准,只是一套开发方式,构架思想 (2)url更加简洁 (3)有利于不同系统之间的资源共享 (二)概述 RESTful具体来 ...
- springMVC入门(六)------json交互与RESTFul风格支持
简介 JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.由于其简单易用,目前常用来通过AJAX与后台进行交互.springMVC对于接收.发送JSON数据也 ...
- 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程【三】——Web Api入门
系列导航地址http://www.cnblogs.com/fzrain/p/3490137.html 前言 经过前2节的介绍,我们已经把数据访问层搭建好了,从本章开始就是Web Api部分了.在正式开 ...
随机推荐
- GUI编程笔记(java)02:java.awt和java.swing包的区别
1. java.awt和java.swing两者的概述 java.awt:(java的标准包) Abstract Window ToolKit (抽象窗口工具包),需要调用本地 ...
- dll注册到GAC还是bin - sharepoint程序
通常来说程序在使用dll的时候,会先去GAC中查找是否有存在合适的dll,然后才会到应用程序下的bin目录去查找: 前几天遇到了一个奇葩问题,web项目工程添加了一个第三方dll的引用,然后把这个第三 ...
- JavaScript 应用开发 #4:切换任务的完成状态
在勾选了任务项目左边的对号(复选框)以后,会将任务的状态标记为已完成,取消勾选的话,又会把任务的状态标记为未完成.所以, 我们需要一个可以切换任务完成状态的方法.在任务模型里面,表示任务状态的属性是 ...
- Ubuntu 13.10 Rhythmbox 播放器不能播放MP3。安装插件
Ctrl+Alt+T > sudo apt-get install ubuntu-restricted-extras 因为版权和专利的问题,MP3等一些non-free的格式文件支持没有出现在免 ...
- CentOS 6.7安装Java JDK
1.下载Java JDK 下载地址:http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.htm ...
- SAMBA用户访问指定的目录
指定某个用户访问一个特定的共享文件夹sfx 用户可以访问abc目录 别的用户不可以访问abc目录 先创建一个用户命令useradd sfx 创建一个smbpasswd用户 在创建这个用户时要先创建一个 ...
- PS之放射背景
效果图 素材 新建图层,填充颜色 新建图层,矩形工具画条形 滤镜-扭曲-极坐标 合并图层,效果如下 新建图层,画一个适当的圆 滤镜-模糊-高斯模糊 将素材人物抠出来放在中间
- Lucene技术杂谈
Lucene教程 1 lucene简介 1.1 什么是lucene Lucene是一个全文搜索框架,而不是应用产品.因此它并不像www.baidu.com 或者google Desktop那么 ...
- ios 字符串替换方法
string=[string stringByReplacingOccurrencesOfString:@"-"withString:@"/"];
- ios专题 - socket(1)
二,BSD socket API 简介 BSD socket API 和 winsock API 接口大体差不多,下面将列出比较常用的 API: API接口 讲解 int socket(int add ...