Spring MVC restful風格之put and delete
阿新 • • 發佈:2019-01-30
由於瀏覽器不支援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; } } }