In the Form form, only get and post methods are supported. In order to implement the put method
1) Configure HiddenHttpMethodFilter in SpringMVC
2) Create a post form on the page
3) Create an input item, name="_method", the value is the specified request method
In the HiddenHttpMethodFilter class
get the value of "_method" and get the new request method.
<input type="hidden" name="_method" value="put" th:if="${employee!=null}"/>
The th tag is the thymeleaf template, which means it will only take effect when employee is not empty, and the put in value is not case-sensitive.
At that time, in the new version of SpringBoot, this put request did not work. The reason is that springboot automatically configures, which helps us omit the first step of configuration. The above code method is to achieve automatic configuration, but because the annotation @ConditionalOnProperty limits automatic configuration, the default false does not enable configuration, so the put submission of the page cannot be used.
Configure in the properties configuration file to enable automatic configuration: spring.mvc.hiddenmethod.filter.enabled=true.
In addition, DELETE requests can also be set in the same way.
<form th:action="@{/emp/}+${emp.id}" method="post"> <input type="hidden" name="_method" value="delete"/> <button type="submit" class="btn btn-sm btn-danger" > 删除</button> </form>
Anyone who has studied mvc knows that if you want to support these two special requests, you must first configure the following filters in web.xml:
<!--增加一个HiddenHttpMethodFilter过滤器:目的是给普通浏览器 增加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>
SpringBoot is not so troublesome, because it has helped us incorporate HiddenHttpMethodFilter into the IOC container by default, so its use is extremely simple:
#开启支持put delete请求的过滤器 spring.mvc.hiddenmethod.filter.enabled=true
You only need to add the following hidden fields to the form form of the post request method:
<!--http请求方式--> <form action="..." method="post"> <input type="hidden" name="_method" value="put" /> <!--value值改成delete 请求方式就为delete了--> </form>
Pay attention to the hidden fields above The name must be "_method". If you want to modify it, you need to add the following bean to the IOC:
@Bean public HiddenHttpMethodFilter hiddenHttpMethodFilter(){ HiddenHttpMethodFilter methodFilter = new HiddenHttpMethodFilter(); methodFilter.setMethodParam("_m");//将隐藏域 _method --> _m return methodFilter; }
The above is the detailed content of How to use PUT and Delete requests in SpringBoot. For more information, please follow other related articles on the PHP Chinese website!