浏览器form表单只支持GET与POST请求,而DELETE、PUT等method并不支持,spring3.0添加了一个过滤器,可以将这些请求转换为标准的http方法,使得支持GET、POST、PUT与DELETE等请求,该过滤器为HiddenHttpMethodFilter。
HiddenHttpMethodFilter的父类是OncePerRequestFilter,它继承了父类的doFilterInternal方法,工作原理是将jsp页面的form表单的method属性值在doFilterInternal方法中转化为标准的Http方法,即GET,、POST、 HEAD、OPTIONS、PUT、DELETE、TRACE,然后到Controller中找到对应的方法。例如,在使用注解时我们可能会在Controller中用于@RequestMapping(value = “list”, method = RequestMethod.PUT),所以如果你的表单中使用的是,那么这个表单会被提交到标了Method="PUT"的方法中。
restful体现
前台
th:href="@{/emp/}+${emp.id}" class="btn btn-sm btn-primary">修改</a>
后台
//修改员工页面
@GetMapping("/emp/{id}")
实际传参样式
<form action="/emp" method="post">
<input type="hidden" name="_method" value="put"/>
<!--
1、SpringMVC中配置HiddenHttpMethodFilter将请求转成指定方式;
2、页面创建一个post表单
3、创建一个input项,name="_method";值就是我们指定的请求方式
-->
该组件SpringBoot已经自动配置好,无需再@Bean组件,但自己用的时候却老是无法映射到Controller里对应的PUT请求,然后去瞄了眼webmvc的自动配置类:
@Bean
@ConditionalOnMissingBean({HiddenHttpMethodFilter.class})
@ConditionalOnProperty(
prefix = "spring.mvc.hiddenmethod.filter",
name = {"enabled"},
matchIfMissing = false
)
public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() {
return new OrderedHiddenHttpMethodFilter();
}
发现较先前版本多了@ConditionalOnProperty的注解,也就是条件引入。查看括号内的内容可以知道,这个组件是否加入容器决定于这个属性,再看下SpringBoot配置的元数据对这个property的说明
{
"name": "spring.mvc.hiddenmethod.filter.enabled",
"type": "java.lang.Boolean",
"description": "Whether to enable Spring's HiddenHttpMethodFilter.",
"defaultValue": false
},
若在ssm框架下实现,需要在web.xml中加如下配置,同时,HiddenHttpMethodFilter必须作用于dispatcher前
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<servlet-name>spring</servlet-name>
</filter-mapping>
若在springboot框架下实现,其实我们就是在配置文件中加这一句,默认是false
spring.mvc.hiddenmethod.filter.enabled = true