DELETE方法在SSM和SpringBoot的应用

Http协议中,四个表示操作方式的动词GET POST PUT DELETE,他们对应四种基本操作,GET用来获取资源,POST用来新建资源,PUT用来更新资源,DELETE用来删除资源

简单的说,就是我们在访问资源时,可以通过这四个状态来表示对于资源的不同操作,这四个状态表现为我们请求的四种方式
/controller/1 HTTP GET :得到id为1 的资源
/controller/1 HTTP DELETE :删除id为1的资源
/controller/1 HTTP PUT :更新id为1 的资源
/controller/1 HTTP POST :增加id为1 的资源

在访问同一个url的时候,通过不同的请求方式,对应到不同的controller处理单元。

但是在我们项目中其实只认识postget请求,delete put都是有post请求映射过去的,在ssm项目和springboot项目中有不同的处理方式。


SSM处理DELETE请求

在我们的ssm项目中,前端的请求需要加上一个字段,名称为_method,值为DELETE。在后台我们需要配置hiddenHttpMethodFilter,来将POST请求转换为PUT或者DELETE请求。

代码

  1. 配置hiddenHttpMethodFilter

    1
    2
    3
    4
    5
    6
    7
    8
    9
    <!--配置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>
  2. 准备页面代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    <form action="myController/testRest/10" method="POST">
    <input type="hidden" name="_method" value="DELETE">
    <input type="submit" value="testPUT">
    </form>
    <br/>
    <form action="myController/testRest/10" method="POST">
    <input type="hidden" name="_method" value="DELETE">
    <input type="submit" value="testDELETE">
    </form>
    <br/>
    <form action="myController/testRest/10" method="POST">
    <input type="submit" value="testPOST">
    </form>
    <br/>
    <form action="myController/testRest/10" method="GET">
    <input type="submit" value="testGET">
    </form>

原理

Filter内部会对post方法进行一个转换。

1
2
3
4
5
6
7
8
9
10
11
12
13
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
HttpServletRequest requestToUse = request;
if ("POST".equals(request.getMethod()) && request.getAttribute("javax.servlet.error.exception") == null) {
String paramValue = request.getParameter(this.methodParam);// "_method"
if (StringUtils.hasLength(paramValue)) {
String method = paramValue.toUpperCase(Locale.ENGLISH);
if (ALLOWED_METHODS.contains(method)) {
requestToUse = new HiddenHttpMethodFilter.HttpMethodRequestWrapper(request, method);
}
}
}
filterChain.doFilter((ServletRequest)requestToUse, response);
}

Springboot

springboot内部已经默认引入了HiddenHttpMethodFilter,可在SpringBoot启动日志里看到该Filter的启动信息。我们只需要修改ajaxtype属性为DELETE就好了。