开发者社区> 问答> 正文

spring mvc接收put请求的数据失败。

controller代码节选:

@RequestMapping(value = "/update/{id}", method = RequestMethod.PUT)
    public String update(HttpServletRequest request,
            HttpServletResponse response, ModelMap modelMap, Equipment equipment) {
        System.out.println(request.getParameter("name"));
        System.out.println(equipment.getIp());
        this.getEquipmentService().update(equipment);
        return "redirect:/equipment/list/json";
    }
前端jQuery的ajax请求代码:
?
1
2
3
function putTest(){
        $.ajax('<%=request.getContextPath()%>/equipment/update/82f1c375-38d0-4c4b-bc15-e81e98fc4506',{type:'post',data:{_method:'put',id:'82f1c375-38d0-4c4b-bc15-e81e98fc4506',name:'设备1',ip:'127.0.0.1',port:'8887',updateTime:'2011-10-09 11:11:56'}});
    }
web.xml添加了HiddenHttpMethodFilter:

<filter>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <servlet-name>DispatcherServlet</servlet-name>
  </filter-mapping>
按上面的配置,在前端点击按钮执行putTest方法后,后台的

System.out.println(request.getParameter("name"));
System.out.println(equipment.getIp());
正常输出数据。
但是把前端的的post方法改成put,后台的数据都接收不了了,输出为null。

$.ajax('<%=request.getContextPath()%>/equipment/update/82f1c375-38d0-4c4b-bc15-e81e98fc4506',{type:'put',data:{_method:'put',id:'82f1c375-38d0-4c4b-bc15-e81e98fc4506',name:'设备1',ip:'127.0.0.1',port:'8887',updateTime:'2011-10-09 11:11:56'}});
在firebug上也没查到有出错的信息。
请问有人做过相同的例子吗?有没有遇过类似问题。put和post方法的区别是什么,数据的发送方式一样的吗?我拿着http的RFC中文文档看得有点不太明白。求解答。

展开
收起
a123456678 2016-07-08 10:28:55 2320 0
1 条回答
写回答
取消 提交回答
  • <form method="POST">这里不要变动。
    
    在form内部加上一hidden域
    
    <input type="hidden" name="_method" value="put" />就可以了。

    浏览器本身只支持get和post方法,使用_method来告知spring这是一个put请求。

    建议你使用spring的taglib,写form会方便很多,还可以绑定model。

    2019-07-17 19:53:09
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Java Spring Boot开发实战系列课程【第7讲】:Spring Boot 2.0安全机制与MVC身份验证实战(Java面试题) 立即下载
Spring Cloud 微服务核心组件集 mica 的设计思路 立即下载
workshop专场-微服务专场-开发者动手实践营-微服务-Spring Cloud Alibaba 微服务全家桶体验 立即下载

相关实验场景

更多