springboot改变表单提交的方式

本文介绍在SpringBoot中如何通过隐藏字段_method实现POST请求转换为PUT请求的方法,适用于同一页面进行新增和修改操作。利用HiddenHttpMethodFilter过滤器,根据_method参数值改变请求方式。

使用场景

如果新增用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();
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值