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

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

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值