您的位置:首页 > 编程语言 > Java开发

Spring MVC REST风格实现PUT、DELETE请求

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

如果通过jQuery发送ajax请求,jQuery是支持put和delete请求的,无需配置过滤器HiddenHttpMethodFilter,也无需隐藏字段”_method”。

web.xml配置:

<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表单:

<form action="/artitle/1234" method="post">
<input type="hidden" name="_method" value="put" />
<input type="text" name="isform" value="yes" />
......
</form>


controller控制器:

@RequestMapping(value = "/artitle/{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;
}


2、无论是form表单还是ajax方式,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>


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

http://blog.csdn.net/u011630575/article/details/50550127
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring mvc