ajax发送PUT/DELETE(restful风格)请求问题及解决办法

Tomcat把请求的数据(实体信息中的数据)封装成一个Map(键值对形式),request.getParameter(“”)就从map中取值,而SpringMVC会把每个属性的值调用getParameter方法封装,而Tomcat看到是PUT/DELETE请求则不会封装请求数据到map,只有POST形式的请求才会封装到请求体。
解决方法1:
配置HiddenHttpMethodFilter,这个类可以把POST转换成对应的_method=?的?号中的内容,从而实现请求.

   <filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class></filter>
 <filter-mapping>
 <filter-name>HiddenHttpMethodFilter</filter-name>
 <url-pattern>/*</url-pattern>
 </filter-mapping>
 
 $.ajax({
url: "${pageContext.request.contextPath}/emp/" + id,
type: "POST",
data: $("#app form").serialize() +"&_method=PUT",
success: function (result) {
    alert("操作成功!");
}
});

解决方法2(推荐):

 <filter>
     <filter-name>HttpPutFormContentFilter</filter-name>
      <filter-    class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
</filter>
  <filter-mapping>
      <filter-name>HttpPutFormContentFilter</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>

ajax部分不做要求:

$.ajax({
    url: "${pageContext.request.contextPath}/emp/" + id,
    type: "PUT",
    data: $("#app form").serialize(),
    success: function (result) {
        alert("操作成功!");
    }
});

参考原文地址:https://www.cnblogs.com/roobtyan/p/9576685.html

猜你喜欢

转载自blog.csdn.net/qq_37514822/article/details/82887298