• 简介

  REST 即 Representational State Transfer。(资源)表现层状态转化。是目前最流行的一种互联网软件架构。它结构清晰、符合标准、易于理解、扩展方便,所以正得到越来越多网站的采用,POST, DELETE, PUT, GET 分别对应 CRUD。Spring3.0 开始支持 REST 风格的请求,是通过 org.springframework.web.filter.HiddenHttpMethodFilter 把 POST 请求转化为 PUT 和 DELETE 请求。本次实验采用的是 Spring4.0 。

  • HiddenHttpMethodFilter 源码
public static final String DEFAULT_METHOD_PARAM = "_method";

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException { String paramValue = request.getParameter(this.methodParam);
if ("POST".equals(request.getMethod()) && StringUtils.hasLength(paramValue)) {
String method = paramValue.toUpperCase(Locale.ENGLISH);
HttpServletRequest wrapper = new HttpMethodRequestWrapper(request, method);
filterChain.doFilter(wrapper, response);
}
else {
filterChain.doFilter(request, response);
}
}

  从 HiddenHttpMethodFilter 的源码可以看出,Spring 根据请求中的 _method 参数进行转化,因此如果想发起 REST 风格的 DELETE 或者 PUT 请求,只需要在表单中带上 _method 参数,并且把 _method 的值设置为 DELETE 或者 PUT(大写) 即可。详细例子如下:

  1. 在 web.xml 中配置 HiddenHttpMethodFilter
  2. 编写 handler 代码
  3. 编写页面
    <!-- 配置 org.springframework.web.filter.HiddenHttpMethodFilter ,可以把 POST 请求转化为 PUT 或者 DELETE 请求 -->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
package rex.springmvc.handlers;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; @RequestMapping(value="/restTest")
@Controller
public class RestTestHandler {
private static final Logger logger = Logger.getLogger(RestTestHandler.class);
private static final String SUCCESS = "success"; @RequestMapping(value="/restGet/{id}", method=RequestMethod.GET)
public String restGet(@RequestParam(value="id", required=false) Integer id){
logger.debug("restGet:" + id);
return SUCCESS;
} @RequestMapping(value="/restPut/{id}", method=RequestMethod.PUT)
public String restPut(@RequestParam(value="id", required=false) Integer id){
logger.debug("restPut:" + id);
return SUCCESS;
} @RequestMapping(value="/restDelete/{id}", method=RequestMethod.DELETE)
public String restDelete(@RequestParam(value="id", required=false) Integer id){
logger.debug("restDelete:" + id);
return SUCCESS;
} @RequestMapping(value="/restPost", method=RequestMethod.POST)
public String restPost(){
logger.debug("restPost");
return SUCCESS;
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Rest Test</title>
</head>
<body>
<br>
<br>
<a href="restTest/restGet/1">Test Rest Get</a> <br>
<br>
<form action="restTest/restPut/1" method="post">
<input type="hidden" name="_method" value="PUT"> <input
type="submit" value="submit">
</form> <br>
<br>
<form action="restTest/restDelete/1" method="post">
<input type="hidden" name="_method" value="DELETE"> <input
type="submit" value="submit">
</form> <br>
<br>
<form action="restTest/restPost" method="post">
<input type="submit" value="submit">
</form>
</body>
</html>

注:handler 中 @RequestParam 注解必须加上 required 参数,否则访问页面会出现400错误。

欢迎转载,转载必须标明出处

SpringMVC REST 风格请求介绍及简单实践的更多相关文章

  1. Thrift简单实践

    0.什么是RPC RPC(Remote Procedure Call - 远程过程调用),是通过网络从远程计算机上请求服务,而不需要了解底层网路技术的细节.简单点说,就是像调用本地服务(方法)一样调用 ...

  2. 学习SpringMVC——如何获取请求参数

    @RequestParam,你一定见过:@PathVariable,你肯定也知道:@QueryParam,你怎么会不晓得?!还有你熟悉的他(@CookieValue)!她(@ModelAndView) ...

  3. JSR 303 - Bean Validation 介绍及最佳实践

    JSR 303 - Bean Validation 介绍及最佳实践 JSR 303 – Bean Validation 是一个数据验证的规范,2009 年 11 月确定最终方案.2009 年 12 月 ...

  4. JAVAEE——SpringMVC第一天:介绍、入门程序、架构讲解、SpringMVC整合MyBatis、参数绑定、SpringMVC和Struts2的区别

    1. 学习计划   第一天 1.SpringMVC介绍 2.入门程序 3.SpringMVC架构讲解 a) 框架结构 b) 组件说明 4.SpringMVC整合MyBatis 5.参数绑定 a) Sp ...

  5. Masonry介绍与使用实践 - iOS移动开发周报

    本文转发至 http://www.tuicool.com/articles/MRbaEnB/ 原文  http://www.infoq.com/cn/news/2014/11/masonry-intr ...

  6. springMVC带参数请求重定向

    SpirngMVC返回逻辑视图名 可以分下面几种情况: 1. servlet进行请求转发,返回到jsp页面,如  return "index.jsp" ; 2. servlet 返 ...

  7. Android 设计随便说说之简单实践(合理组合)

    上一篇(Android 设计随便说说之简单实践(模块划分))例举了应用商店设计来说明怎么做模块划分.模块划分主要依赖于第一是业务需求,具体是怎么样的业务.应用商店则包括两个业务,就是向用户展示appl ...

  8. python模块介绍- HTMLParser 简单的HTML和XHTML解析器

    python模块介绍- HTMLParser 简单的HTML和XHTML解析器 2013-09-11 磁针石 #承接软件自动化实施与培训等gtalk:ouyangchongwu#gmail.comqq ...

  9. 快速构建Windows 8风格应用21-构建简单媒体播放器

    原文:快速构建Windows 8风格应用21-构建简单媒体播放器 本篇博文主要介绍如何构建一个简单的媒体播放器. <快速构建Windows 8风格应用20-MediaElement>博文中 ...

随机推荐

  1. 【iOS 录音转码MP3及转码BASE64上传】

    iOS 录音转码MP3及转码BASE64上传 一,开始录音 NSLog(@"开始录音"); [self startRecord]; - (void)startRecord { // ...

  2. GitLab Wiki 内容恢复版本管理

    原来一直在网站上写Wiki文档, 最近手欠误删一篇文档, 想要恢复文档时才发现原来gitlab的Wiki是用git管理的从此再也不用为误删担心了 实现步骤: mac系统安装gollow brew in ...

  3. Git本地操作相关介绍

    本地使用git时遇到问题及解决方案总结: 1.git push origin master 后,终端上出现错误信息: push失败,原因多半是因为github上远程仓库中有Reademe.md文件 解 ...

  4. phpcms如何做企业站--> 替换首页最初操作

    首先用一个静态首页的模板,通过cms进行替换做成一个有后台的 首页的替换流程首先要先把静态网页做出来,拿这个页面去替换 页面所有的文件都在这,做静态页面的文件 现在要做的是把这些文件复制一下拿到php ...

  5. Spark源码分析之Spark Shell(下)

    继上次的Spark-shell脚本源码分析,还剩下后面半段.由于上次涉及了不少shell的基本内容,因此就把trap和stty放在这篇来讲述. 上篇回顾:Spark源码分析之Spark Shell(上 ...

  6. ES(二): Build ES Cluster on Azure VM

    目录: 系统环境准备 安装ES集群 安装Kibana 安装x-pack 安装head 系统环境准备 参见: HDP2.4安装(二):Centos7配置 修改network: 修改hosts: 配置ss ...

  7. show_you_my_codes 001

    program 001 第 0001 题:做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券), 使用 Python 如何生成 200 个激活码(或者优 ...

  8. 单点登录实现(spring session+redis完成session共享)

    一.前言 项目中用到的SSO,使用开源框架cas做的.简单的了解了一下cas,并学习了一下 单点登录的原理,有兴趣的同学也可以学习一下,写个demo玩一玩. 二.工程结构 我模拟了 sso的客户端和s ...

  9. 【转】对于HttpClient和HtmlUnit的理解

    原文地址:http://www.haohaoblog.com/?p=1327&utm_source=tuicool 做Java编程的人其实,很多不懂SEO,也不知道如何让百度收录等等,当然,对 ...

  10. Nginx+tomcat动静分离安装脚本

    #!/bin/bashsetenforce 0systemctl stop firewalldtar -zxvf nginx-1.8.0.tar.gz -C /usr/src/ cd /usr/src ...