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请求作为案例,



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,现在已经可以成功的获取并打印出前台的参数。

参考:http://my.oschina.net/buwei/blog/191942

猜你喜欢

转载自rd-030.iteye.com/blog/2318949