SpringMVC控制器接收不了PUT提交的参数的解决方案

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

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


 /**
* 配置项的更新
*
* @param configId
* @param value
*
* @return
*/
@RequestMapping(value = "/item/{configId}", method = RequestMethod.PUT)
@ResponseBody
public JsonObjectBase updateItem(@PathVariable long configId, String value) {

// 业务校验
configValidator.validateUpdateItem(configId, value);

LOG.info("start to update config: " + configId);

//
// 更新, 并写入数据库
//
String emailNotification = "";
emailNotification = configMgr.updateItemValue(configId, value);

//
// 通知ZK
//
configMgr.notifyZookeeper(configId);

return buildSuccess(emailNotification);
}


很常规的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请求作为案例,

[img]http://static.oschina.net/uploads/space/2014/0110/095835_Gg3l_919487.jpg[/img]

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请求,参数基本都不变

[img]http://static.oschina.net/uploads/space/2014/0110/101133_BTpc_919487.jpg[/img]

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

参考:http://my.oschina.net/buwei/blog/191942
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值