本文主要是介绍Spring MVC RestFul 中的 DELETE 传输方式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在Spring RestFul 中 当浏览器不支持PUT和DELETE传输协议时,可以在表单中添加一个隐藏域,此隐藏于的name属性为:_method如:
<form action="update" method="post">...<input type="hidden" name="_method" value="PUT"/>
</form>
但是Spring中默认的方法过滤器(org.springframework.web.filter.HiddenHttpMethodFilter)是只对POST传输协议进行判断。
自定义实现对GET的支持
public class MyHiddenHttpMethodFilter extends HiddenHttpMethodFilter{private String methodParam = DEFAULT_METHOD_PARAM;public void setMethodParam(String methodParam){Assert.hasText(methodParam, "'methodParam' must not be empty");this.methodParam = methodParam;}@Overrideprotected void doFilterInternal(HttpServletRequest request,HttpServletResponse response, FilterChain filterChain)throws ServletException, IOException {String paramValue = request.getParameter(methodParam);String _method = request.getMethod();if (StringUtils.hasLength(paramValue)) {String method = paramValue.toUpperCase(Locale.ENGLISH);boolean b = ("POST".equals(_method) && "PUT".equalsIgnoreCase(method)) || ( "GET".equals(_method) && "DELETE".equalsIgnoreCase(method));if( b ){HttpServletRequest wrapper = new HttpMethodRequestWrapper(request, method);filterChain.doFilter(wrapper, response);}else{}}else {filterChain.doFilter(request, response);}}private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {private final String method;public HttpMethodRequestWrapper(HttpServletRequest request, String method) {super(request);this.method = method;}@Overridepublic String getMethod() {return this.method;}}}
此类的实现是当使用DELETE协议时请求使用GET然后加上参数_method=DELETE;当使用PUT协议时请求使用POST然后加上_method=PUT
这篇关于Spring MVC RestFul 中的 DELETE 传输方式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!