spring MVC (5) 利用HiddenHttpMethodFilter来讲post请求变成put或者delete请求

一,请求的方式
HTTP 协议里面,四个表示操作方式的动
词:GET、POST、PUT、DELETE。它们分别对应四种基本操作:GET 用来获
取资源,POST 用来新建资源,PUT 用来更新资源,DELETE 用来删除资源。
在页面上使用HiddenHttpMethodFilter将post请求变成put或者delete请求
二,转化请求的步骤
1,在web.xml中配置HiddenHttpMethodFilter,如下:

<filter>
      <filter-name>HiddenHttpMethodFilterfilter-name>
      <filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
    filter>
    <filter-mapping>
      <filter-name>HiddenHttpMethodFilterfilter-name>
      /*
    filter-mapping>

注:在filter中filter-name一定要放在filter-class前面,否则会报错
2,页面代码

"RequestMappingTest/testDelete/1" method="post"> type="hidden" name="_method" value="DELETE"> type="submit" value="Delete">


"RequestMappingTest/testPut/1" method="post"> type="hidden" name="_method" value="PUT"> type="submit" value="put">

3,实现类的代码

  @RequestMapping(value="/testDelete/{id}",method=RequestMethod.DELETE)
    public String deleteTest(@PathVariable("id") Integer id) {
        System.out.println("deleteTest:"+id);
        return "success";
    }
    @RequestMapping(value="/testPut/{id}",method=RequestMethod.PUT)
    public String putTest(@PathVariable("id") Integer id) {
        System.out.println("putTest:"+id);
        return "success";
    }

三,HiddenHttpMethodFilter类的源码

HiddenHttpMethodFilter的实现原理其实就是新建了个HttpMethodRequestWrapper类,覆写了getMethod()方法,也就是将原来本身的HTTP请求方式(POST)给隐藏掉了。

public class HiddenHttpMethodFilter extends OncePerRequestFilter {
    public static final String DEFAULT_METHOD_PARAM = "_method";
    private String methodParam = DEFAULT_METHOD_PARAM;
    public void setMethodParam(String methodParam) {
        Assert.hasText(methodParam, "'methodParam' must not be empty");
        this.methodParam = methodParam;
    }
    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);
        }
    }
    private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {
        private final String method;
        public HttpMethodRequestWrapper(HttpServletRequest request, String method) {
            super(request);
            this.method = method;
        }
        public String getMethod() {
            return this.method;
        }
    }
}

你可能感兴趣的:(SpringMVC)