使用场景
如果新增用post提交表单,修改用put提交表单,而且还想共用同一个页面,就可以使用这种方式
html页面
<form th:action="@{/user/emp}" method="post">
<input type="hidden" name="_method" value="put" th:if="${bean != null}">
如果bean存在,说明是修改,input就会起作用,如果是新增页面bean不是null这个input不会被编译。
原理
springboot为我们配置了HiddenHttpMethodFilter拦截器
@Bean
@ConditionalOnMissingBean({HiddenHttpMethodFilter.class})
public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() {
return new OrderedHiddenHttpMethodFilter();
}
public class OrderedHiddenHttpMethodFilter extends HiddenHttpMethodFilter implements Ordered {}
public class HiddenHttpMethodFilter extends OncePerRequestFilter {
private String methodParam = "_method";
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);
if (StringUtils.hasLength(paramValue)) {
requestToUse = new HiddenHttpMethodFilter.HttpMethodRequestWrapper(request, paramValue);
}
}
filterChain.doFilter((ServletRequest)requestToUse, response);
}
}
springboot 为我们配置了OrderedHiddenHttpMethodFilter过滤器,他从每个过来的post请求中获取名为_method的参数值,如果这个参数值不为空,那么就会将请求转化为响应的方式。
说明
高springboot版本可能需要在配置文件中配置
spring.mvc.hiddenmethod.filter=true
原因
@Bean
@ConditionalOnMissingBean({HiddenHttpMethodFilter.class})
//使用ConditionalOnProperty注解 只有spring.mvc.hiddenmethod.filter=true的时候这个组件才能被加载到容器当中
@ConditionalOnProperty(
prefix = "spring.mvc.hiddenmethod.filter",
name = {"enabled"},
matchIfMissing = true
)
public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() {
return new OrderedHiddenHttpMethodFilter();
}
本文介绍在SpringBoot中如何通过隐藏字段_method实现POST请求转换为PUT请求的方法,适用于同一页面进行新增和修改操作。利用HiddenHttpMethodFilter过滤器,根据_method参数值改变请求方式。
3706

被折叠的 条评论
为什么被折叠?



