1)REST具体表现:

--- /account/1  HTTP GET       获取id=1的account

--- /account/1  HTTP DELETE 删除id=1的account

--- /aacount/1  HTTP PUT        更新id=1的account

--- /account      HTTP POST     新增account

2)SpringMVC中如何实现REST?

众所周知,浏览器form表单只支持GET与POST请求,而DELETE、PUT等method并不支持。Spring3.0增加了一个过滤器,可以将这些请求转化为标准的http方法,使得支持GET、POST、PUT及DELETE请求。

这个过滤器就是:org.springframework.web.filter.HiddenHttpMethodFilter

 package org.springframework.web.filter;

 import java.io.IOException;
import java.util.Locale;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse; import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.util.WebUtils; /**
* {@link javax.servlet.Filter} that converts posted method parameters into HTTP methods,
* retrievable via {@link HttpServletRequest#getMethod()}. Since browsers currently only
* support GET and POST, a common technique - used by the Prototype library, for instance -
* is to use a normal POST with an additional hidden form field ({@code _method})
* to pass the "real" HTTP method along. This filter reads that parameter and changes
* the {@link HttpServletRequestWrapper#getMethod()} return value accordingly.
*
* <p>The name of the request parameter defaults to {@code _method}, but can be
* adapted via the {@link #setMethodParam(String) methodParam} property.
*
* <p><b>NOTE: This filter needs to run after multipart processing in case of a multipart
* POST request, due to its inherent need for checking a POST body parameter.</b>
* So typically, put a Spring {@link org.springframework.web.multipart.support.MultipartFilter}
* <i>before</i> this HiddenHttpMethodFilter in your {@code web.xml} filter chain.
*
* @author Arjen Poutsma
* @author Juergen Hoeller
* @since 3.0
*/
public class HiddenHttpMethodFilter extends OncePerRequestFilter { /** Default method parameter: {@code _method} */
public static final String DEFAULT_METHOD_PARAM = "_method"; private String methodParam = DEFAULT_METHOD_PARAM; /**
* Set the parameter name to look for HTTP methods.
* @see #DEFAULT_METHOD_PARAM
*/
public void setMethodParam(String methodParam) {
Assert.hasText(methodParam, "'methodParam' must not be empty");
this.methodParam = methodParam;
} @Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException { HttpServletRequest requestToUse = request; if ("POST".equals(request.getMethod()) && request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == null) {
String paramValue = request.getParameter(this.methodParam);
if (StringUtils.hasLength(paramValue)) {
requestToUse = new HttpMethodRequestWrapper(request, paramValue);
}
} filterChain.doFilter(requestToUse, response);
} /**
* Simple {@link HttpServletRequest} wrapper that returns the supplied method for
* {@link HttpServletRequest#getMethod()}.
*/
private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper { private final String method; public HttpMethodRequestWrapper(HttpServletRequest request, String method) {
super(request);
this.method = method.toUpperCase(Locale.ENGLISH);
} @Override
public String getMethod() {
return this.method;
}
} }

从这个filter代码中可以得知,该filter是通过POST方式提交表单,该表单中包含一个名称为_method的隐藏域,该隐藏域的值用来判定将要转化的请求方式。所谓的转化请求方式,就是在该filter中重新生成了一个新的、标准化的请求。

3)如何使用到springmvc项目中?

步骤一:在web.xml中添加filter配置:

    <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>

步骤二:在HelloWord.java中添加get/post/put/delete方法:

 package com.dx.springlearn.handlers;

 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; @Controller
@RequestMapping("class_requestmapping")
public class HelloWord {
private static String SUCCESS = "success"; @RequestMapping(value = "/accountDelete/{id}", method = RequestMethod.DELETE)
public String accountDelete(@PathVariable("id") Integer id) {
System.out.println("test rest DELETE,account id:" + id);
return SUCCESS;
} @RequestMapping(value = "/accountPut/{id}", method = RequestMethod.PUT)
public String accountPut(@PathVariable("id") Integer id) {
System.out.println("test rest PUT,account id:" + id);
return SUCCESS;
} @RequestMapping(value = "/account", method = RequestMethod.POST)
public String account() {
System.out.println("test rest POST");
return SUCCESS;
} @RequestMapping(value = "/account/{id}", method = RequestMethod.GET)
public String account(@PathVariable("id") Integer id) {
System.out.println("test rest GET,account id:" + id);
return SUCCESS;
}
}

步骤三:在index.jsp中添加get/post/put/delete方法请求的html脚本:

    <!-- delete提交 -->
<form id="form_testRestMethod_DELETE" name="form_testRestMethod_DELETE" method="POST"
action="class_requestmapping/accountDelete/2">
<input type="hidden" name="_method" value="DELETE" />
<button name="submit" id="submit">test rest DELETE</button>
</form>
<br>
<!-- put提交 -->
<form id="form_testRestMethod_PUT" name="form_testRestMethod_PUT" method="POST"
action="class_requestmapping/accountPut/2">
<input type="hidden" name="_method" value="PUT" />
<button name="submit" id="submit">test rest PUT</button>
</form>
<br>
<!-- post提交 -->
<form id="form_testRestMethod_POST" name="form_testRestMethod_POST"
method="POST" action="class_requestmapping/account">
<button name="submit" id="submit">test rest POST</button>
</form>
<br>
<!-- get提交 -->
<a href="class_requestmapping/account/1">test rest GET</a>
<br>

步骤四:测试打印结果为:

test rest GET,account id:1
test rest POST
test rest PUT,account id:2
test rest DELETE,account id:2

SpringMVC(四):@RequestMapping结合org.springframework.web.filter.HiddenHttpMethodFilter实现REST请求的更多相关文章

  1. SpringMVC(四) RequestMapping请求方式

    常见的Rest API的Get和POST的测试参考代码如下,其中web.xml和Springmvc的配置文件参考HelloWorld测试代码中的配置. 控制类的代码如下: package com.ti ...

  2. java.lang.ClassCastException: org.springframework.web.filter.CharacterEncodingFilter cannot be cast

    严重: Exception starting filter encodingFilterjava.lang.ClassCastException: org.springframework.web.fi ...

  3. java.lang.ClassNotFoundException: org.springframework.web.filter.CharacterEncodingFilter

    今天在用git merge 新代码后报了如下错误:java.lang.ClassNotFoundException: org.springframework.web.filter.CharacterE ...

  4. org.springframework.web.filter.CharacterEncodingFilter

    感谢:http://blog.csdn.net/heidan2006/article/details/3075730 很简单很实用的一个过滤器,当前台JSP页面和JAVA代码中使用了不同的字符集进行编 ...

  5. 通过org.springframework.web.filter.CharacterEncodingFilter定义Spring web请求的编码

    通过类org.springframework.web.filter.CharacterEncodingFilter,定义request和response的编码.具体做法是,在web.xml中定义一个F ...

  6. org.springframework.web.filter.DelegatingFilterProxy的理解

    org.springframework.web.filter.DelegatingFilterProxy可以将filter交给spring管理. 我们web.xml中配置filter时一般采用下面这种 ...

  7. java.lang.ClassCastException: org.springframework.web.filter.CharacterEncodingFilter cannot be cast to javax.servlet.Filter

    java.lang.ClassCastException: org.springframework.web.filter.CharacterEncodingFilter cannot be cast ...

  8. org.springframework.web.filter.DelegatingFilterProxy的作用

    一.类结构 DelegatingFilterProxy类继承GenericFilterBean,间接实现了Filter,故而该类属于一个过滤器.那么就会有实现Filter中init.doFilter. ...

  9. Caused by: java.lang.ClassNotFoundException: org.springframework.web.filter.FormContentFilter

    又是一个报错,我写代码真的是可以,所有的bug都会被我遇到,所有的问题我都能踩一遍,以前上学的时候同学就喜欢问我问题,因为他们遇到的问题,我早就遇到了......... 看看报错内容: 2019-04 ...

随机推荐

  1. 关于脱离laravel框架使用Illuminate/Validation验证器

    1.关于Illuminate/Validation验证器 Validation 类用于验证数据以及获取错误消息. github地址:github.com/illuminate/validation 文 ...

  2. Pick up lines搭讪

    1.In a bar Do you come here often? I've never seen you here before. What do you think of this bar? A ...

  3. Omron 论坛软件下载连接

    全部软件目录 (更新时间:2017年1月5日) 序号 产品类别 软件名称 1 FA自动化设备 RFID系统 V600-CA5DUSB驱动程序 2 FA自动化设备 可编程控制器 CJ2/CP1USB驱动 ...

  4. HashMap的底层原理

    简单说: 底层原理就是采用数组加链表: 两张图片很清晰地表明存储结构: 既然是线性数组,为什么能随机存取?这里HashMap用了一个小算法,大致是这样实现: // 存储时: int hash = ke ...

  5. 初始配置JDK

    什么是java? java是一门编程语言  编程语言有很多种 你比如 C语言 等等 为什么学习java呢! 因为你要和计算机交互  当然了你用汉语跟她说她听不懂 所以你要学习编程语言 那么额咱们的ja ...

  6. 关于Redis数据库 ---- 基础篇

    Redis数据库也被称为数据结构数据库,因为存储基于key-value模式. 其中,value值可以为字符串(string),哈希(map),列表(list),集合(set)和有序集合(zset). ...

  7. 一个非常标准的连接Mysql数据库的示例代码

    一.About Mysql 1.Mysql 优点 体积小.速度快.开放源码.免费 一般中小型网站的开发都选择 MySQL ,最流行的关系型数据库 LAMP / LNMP Linux作为操作系统 Apa ...

  8. 随机四则运算的出题程序java

    一.设计思想 1.功能较多必须有菜单选择项,将一个大程序分为若干个功能模块的小程序,逐个实现2.针对题目避免重复时先将已生成的算式保存,然后将下一条生成的式子进行判断是否已生成,如果生成则返回循环语句 ...

  9. XML使用练习

    #!/usr/bin/env python # -*- coding:utf-8 -*- import requests from xml.etree import ElementTree as ET ...

  10. iOS开发所有KeyboardType与图片对应展示

    1.UIKeyboardTypeAlphabet 2.UIKeyboardTypeASCIICapable 3.UIKeyboardTypeDecimalPad  4.UIKeyboardTypeDe ...