浏览器本身只支持post和get请求,若想使用put和delete请求springMvc提供了一个过滤器:HiddenHttpMethodFilter
使用这个过滤器需要在web.xml中配置
public class HiddenHttpMethodFilter extends OncePerRequestFilte{
/** Default method parameter: <code>_method</code> */
public static final String DEFAULT_METHOD_PARAM = "_method";
private String methodParam = DEFAULT_METHOD_PARAM;
/**
* Set the parameter name to look for HTTP methods.
* @see #DEFAULT_METHOD_PARAM
*/
public void setMethodParam(String methodParam) {
Assert.hasText(methodParam, "'methodParam' must not be empty");
this.methodParam = methodParam;
}
@Override
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方法传过来_method的值(put delete不区别大小写),在doFilterInternal方法中转化为标准的的http方法
注意:必须是post请求并且带上参数名为_method值为put或delete的请求才可以转化成浏览器不支持的put或delete请求。
前台示例-表单提交方式
<form action="<%=path%>/testDelete" method="post">
<label>姓名:</label>
<input name='usrName' id='usrName' type='text'>
<label>年龄:</label>
<input name='usrAge' id='usrAge' maxlength='50' type='text'>
<input type='hidden' name="_method" value="delete">
<input type="submit" >
</form>
前台示例-ajax提交方式
$.ajax({
type : ‘POST’,
url : path+’/testDelete’,
data: {
_method: ‘DELETE’,
usrName: “张三”,
usrAge : “12”
},
dataType : “json”,
success:function(data){
}
});
后台控制器
@RequestMapping(value="/testDelete",method=RequestMethod.DELETE)
@ResponseBody
public Object testDelete(@RequestParam("usrName")String name,@RequestParam("usrAge")String age){
Syste·m.out.println("DELETE请求");
System.out.println("年龄:"+age);
System.out.println("姓名:"+name);
return SUCCESS;
}