Spring Boot实践--PUT请求不能接收到参数的问题

简介:

项目改造了下框架,把控制器的API全部REST化,不做不知道,SpringMVC的REST有各种坑让你去跳,顺利绕过它们花了我不少时间,这次来提下SpringMVC的PUT提交参数为null的情况。

不过发现了一个很好玩的现象:就是当PUT参数接收为空的时候,前台是正确传值,后端接收对象映射不上,即为空,通过打印:request.getInputStream流里的内容,发现是有参数的,就是没有映射进来,其实是:spring默认没有开启。

1:JSON提交方式: Content-Type:application/json

   后端:对象接收:除了:get请求,不需要增加@ReqeustBody注解,其它的都需要。

            参数接收:使用:@RequestParam 或者不用。

 使用这种请求: 其它后端同事开发的时候:客户端(SOAP)模拟请求时,有了@ReqeustBody参数接收不到,于是去掉,前端开发时,更新代码又加上。因为公司网不能下载插件,后换成了:form表单提交。

2:form表单提交方式:Content-Type:application/x-www-form-urlencoded  

    form表单数据格式:为:param1=111&param2=222 这种开式。

后端:对象接收:除了:所有请求:都不加@ReqeustBody注解

         参数接收:可以使用:@RequestParam 或者不用。

SpringBoot解决方式:

//使用@bean注解
@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    // 就是这个
    @Bean
    public HttpPutFormContentFilter httpPutFormContentFilter() {
        return new HttpPutFormContentFilter();
    }

}

//或者使用:@Component,其实原理都是一样,就是开启:HttpPutFormContentFilter
@Component
public class PutFilter extends HttpPutFormContentFilter {
}

SpringMVC解决方式:

这种方式来自:SpringMVC控制器接收不了PUT提交的参数的解决方案

照常先贴出我的控制器代码,没什么特别的,就是打印出接受到的前台参数值: 

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
	@ResponseBody
	public Map<String, Object> update(
			@RequestParam(value = "isform", required = false) String isform,
			@PathVariable("id") String id) {
		System.out.println("id value: " + id);
		System.out.println("isform value: " + isform);

		return null;

	}

很常规的PUT控制器,用来修改原有的记录,原有的的web.xml中,我只添加了一个和REST涉及的过滤器 

org.springframework.web.filter.HiddenHttpMethodFilter 

<filter>
		<filter-name>HttpMethodFilter</filter-name>
		<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>HttpMethodFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

这个因为大多数人都知道它的作用,这里再啰嗦提一下: 

    浏览器form表单只支持GET与POST请求,而DELETE、PUT等method并不支持,spring3.0添加了一个过滤器,可以将这些请求转 换为标准的http方法,使得支持GET、POST、PUT与DELETE请求,该过滤器为HiddenHttpMethodFilter,只需要在表单中添加一个隐藏字段"_method" 

<form action="..." method="post">  
            <input type="hidden" name="_method" value="put" />  
            ......  
    </form>

下边我们来看下,运行的结果,我会在我的前台发起一个PUT请求作为案例, 

我们来看下后台的参数打印情况: 

id参数顺利的获取到了,因为它其实是由@PathVariable获取的,这个没有什么问题,但是http body中提交的参数值isform却为null,查询了一番,原因是:

如果是使用的是PUT方式,SpringMVC默认将不会辨认到请求体中的参数,或者也有人说是Spirng MVC默认不支持 PUT请求带参数,

解决方案也很简单,就是在web.xml中把原来的过滤器改一下,

换成org.springframework.web.filter.HttpPutFormContentFilter 

<filter>
		<filter-name>HttpMethodFilter</filter-name>
		<filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>HttpMethodFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

在更改之后我们继续一下刚才的案例,发送一个PUT请求,参数基本都不变 

看下后台打印的结果: 

ok,现在已经可以成功的获取并打印出前台的参数。

猜你喜欢

转载自my.oschina.net/spinachgit/blog/1802199