SpringBoot2 PUT请求接收不了参数

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

SpringBoot2 PUT请求接收不了参数

Moshow郑锴   2022-09-08 我要评论

SpringBoot2之PUT请求接收不了参数的解决办法,这个问题,关乎两个Filter过滤器,是spring3和3.5之后提供的,目的就是解决RESTful中PUT请求或者其他请求的问题。

下面请看详细内容

HiddenHttpMethodFilter

html中form表单只支持GET与POST请求,而DELETE、PUT等method并不支持,spring3添加了一个过滤器,可以将这些请求转换为标准的http方法,使得支持GET、POST、PUT与DELETE请求。

    @Bean
    public FilterRegistrationBean<HiddenHttpMethodFilter> testFilterRegistration3() {
        FilterRegistrationBean<HiddenHttpMethodFilter> registration = new FilterRegistrationBean<HiddenHttpMethodFilter>();
        registration.setFilter(new HiddenHttpMethodFilter());//添加过滤器
        registration.addUrlPatterns("/*");//设置过滤路径,/*所有路径
        registration.setName("HiddenHttpMethodFilter");//设置优先级
        registration.setOrder(2);//设置优先级
        return registration;
    }

在页面的form表单中设置method为Post,并添加一个如下的隐藏域:

<input type="hidden" name="_method" value="put" />

查看HiddenHttpMethodFilter源码

        String paramValue = request.getParameter(methodParam);  
        if("POST".equals(request.getMethod()) && StringUtils.hasLength(paramValue)) {  
            String method = paramValue.toUpperCase(Locale.ENGLISH);  
            HttpServletRequest wrapper = new HttpMethodRequestWrapper(request, method); 
            filterChain.doFilter(wrapper, response);  
        } else  
        {  
            filterChain.doFilter(request, response);  
        }  
}  

 由源码可以看出,filter只对Post方法进行过滤,且需要添加参数名为_method的隐藏域,也可以设置其他参数名,比如想设置为_method_,可以在HiddenHttpMethodFilter配置类中设置初始化参数:put (methodParam,"_method_") 

HttpPutFormContentFilter

由HiddenHttpMethodFilter可知,html中的form的method值只能为post或get,我们可以通过HiddenHttpMethodFilter获取put表单中的参数键值对,而在Spring3中获取put表单的参数键值对还有另一种方法,即使用HttpPutFormContentFilter过滤器。

    @Bean
    public FilterRegistrationBean<HttpPutFormContentFilter> testFilterRegistration2() {
        FilterRegistrationBean<HttpPutFormContentFilter> registration = new FilterRegistrationBean<HttpPutFormContentFilter>();
        registration.setFilter(new HttpPutFormContentFilter());//添加过滤器
        registration.addUrlPatterns("/*");//设置过滤路径,/*所有路径
        registration.setName("HttpPutFormContentFilter");//设置优先级
        registration.setOrder(2);//设置优先级
        return registration;
    }

HttpPutFormContentFilter过滤器的作为就是获取put表单的值,并将之传递到Controller中标注了method为RequestMethod.put的方法中。

与HiddenHttpMethodFilter不同,在form中不用添加参数名为_method的隐藏域,且method不必是post,直接写成put,但该过滤器只能接受enctype值为application/x-www-form-urlencoded的表单,也就是说,在使用该过滤器时,form表单的代码必须如下:

<form action="" method="put" enctype="application/x-www-form-urlencoded">  
    ......  
</form>  

另外,经过测试,json数据也是ok的,enctype=”application/json”也是ok的

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们