在web.xml中新增过滤器
<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>
需要注意的是,只有context-type:application/x-www-form-urlencoded的请求才会被过滤。
该过滤器的核心方法如下:
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String paramValue = request.getParameter(this.methodParam);
if ("POST".equals(request.getMethod()) && StringUtils.hasLength(paramValue)) {
String method = paramValue.toUpperCase(Locale.ENGLISH);
HttpServletRequest wrapper = new HttpMethodRequestWrapper(request, method);
filterChain.doFilter(wrapper, response);
}
else {
filterChain.doFilter(request, response);
}
}
将post方法转换为标准的put或者delete方法
前端ajax访问时实例代码如下:
$.ajax({
type : "POST",
url : "student",
dataType : "json",
async : false,
data : {
provinceIds : array,
//该参数指定后台接受方法类型,put/delete
_method : "delete",
},
success : function(data) {
});
后台接受方法:
@RequestMapping(value="student",method = RequestMethod.DELETE, produces = {"text/javascript;charset=UTF-8"})
public String del(HttpServletRequest request, HttpServletResponse response)
{
return null;
}