解决在springMVC框架下put,delete请求无法传参问题
2023.4.10
实际上碰到这个问题基本上都是Tomcat的问题。
Tomcat把请求的数据(实体信息中的数据)封装成一个Map(键值对形式),request.getParameter("")
就从map中取值,而SpringMVC会把每个属性的值调用getParameter
方法封装,而Tomcat看到是PUT请求则不会封装请求数据到map,只有POST形式的请求才会封装到请求体。
Tomcat官方在设计Tomcat时就出现了问题,在tomcat的源码中(大概在3100行左右)其中有个方法parseParameters()
中有段代码如下:
if(!getConnector().isParseBodyMethod(getMethod())){
success =true;
return;
}
这段代码就是在判断请求体中的方法类型和定义的方法类型是否相同,这个定义的方法类型就是POST,如果相同,则封装;如果不同,直接返回。
解决方案
- 只解决put请求(不推荐,既然都用put方法了,delete基本也要用,全当了解就行)
web.xml中配置
<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 (res) {
alert("操作成功!");
}
});
- 解决put、delete请求
web.xml中配置
<!-- 使用Rest风格的URI 将页面普通的post请求转为指定的delete或者put请求-->
<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请求使用如下形式
$.ajax({
url: 'http://localhost:8080/admin/teacher/delete',
data: {'id':data.id,_method:'delete'},
type: 'post',
dataType: 'json',
success: function (res) {
}
})