由于浏览器不支持PUT和DELETE方法,那么我们如何通过Spring实现PUT和DELETE的rest风格呢?
步骤一:
在web.xml中添加一个Spring的过滤器HiddenHttpMethodFilter,对DispatcherServlet进行预处理
<!-- spring mvc 实现delete、put的restful风格过滤器 start-->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<!-- DispatcherServlet 对应的servlet-name-->
<servlet-name>dispatcher</servlet-name>
</filter-mapping>
<!-- spring mvc 实现delete、put的restful风格过滤器 end-->
步骤二:
向后台提交请求时,将请求类型设置为“POST”,同时向后台传递一个参数"_method",参数值可以设置为PUT或DELETE
Demo:ajax 删除restful风格
deleteById:function(id,callback){
//基础验证
var url = controllerUtil.controllers.deleteById;
if(url.trim().length<=0){
throw new Error("please init controllerUtil.controllers.deleteById first.");
}
console.log("id:"+id);
$.ajax({
url : url+"/"+id,
type : "POST",
data : {_method:"DELETE"},
dataType : "json",
async : true,
success : function(ajaxResult) {
callback(ajaxResult);
},
error : function(error) {
alert("error");
}
});
}
/**
* 删除节点
* @param node
* @return
*/
@RequestMapping(value="/node/{id}",method=RequestMethod.DELETE)
@ResponseBody
public AjaxResult deleteTreeNode(@PathVariable("id")Long id) {
getService().deleteById(id);
return AjaxResult.getInstance();
}
以下是Spring过滤器的实现:
public class HiddenHttpMethodFilter extends OncePerRequestFilter {
/** Default method parameter: {@code _method} */
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);
}
}
/**
* Simple {@link HttpServletRequest} wrapper that returns the supplied method for
* {@link HttpServletRequest#getMethod()}.
*/
private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {
private final String method;
public HttpMethodRequestWrapper(HttpServletRequest request, String method) {
super(request);
this.method = method;
}
@Override
public String getMethod() {
return this.method;
}
}
}