Spring MVC RestFul 中的 DELETE 传输方式

来源:互联网 发布:电商平台数据库设计 编辑:程序博客网 时间:2024/06/02 06:43

   在Spring RestFul 中 当浏览器不支持PUT和DELETE传输协议时,可以在表单中添加一个隐藏域,此隐藏于的name属性为:_method如:

        

<form action="update" method="post">    ...    <input type="hidden" name="_method" value="PUT"/></form>
  

   但是Spring中默认的方法过滤器(org.springframework.web.filter.HiddenHttpMethodFilter)是只对POST传输协议进行判断。

   自定义实现对GET的支持

      

public class MyHiddenHttpMethodFilter extends HiddenHttpMethodFilter{private String methodParam = DEFAULT_METHOD_PARAM;public void setMethodParam(String methodParam){Assert.hasText(methodParam, "'methodParam' must not be empty");this.methodParam = methodParam;}@Overrideprotected void doFilterInternal(HttpServletRequest request,HttpServletResponse response, FilterChain filterChain)throws ServletException, IOException {String paramValue = request.getParameter(methodParam);String _method = request.getMethod();if (StringUtils.hasLength(paramValue)) {String method = paramValue.toUpperCase(Locale.ENGLISH);boolean b = ("POST".equals(_method) && "PUT".equalsIgnoreCase(method)) || ( "GET".equals(_method) && "DELETE".equalsIgnoreCase(method));if( b ){HttpServletRequest wrapper = new HttpMethodRequestWrapper(request, method);filterChain.doFilter(wrapper, response);}else{}}else {filterChain.doFilter(request, response);}}private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {private final String method;public HttpMethodRequestWrapper(HttpServletRequest request, String method) {super(request);this.method = method;}@Overridepublic String getMethod() {return this.method;}}}

   此类的实现是当使用DELETE协议时请求使用GET然后加上参数_method=DELETE;当使用PUT协议时请求使用POST然后加上_method=PUT

原创粉丝点击