Spring MVC RestFul 中的 DELETE 传输方式

   在Spring RestFul 中 当浏览器不支持PUT和DELETE传输协议时,可以在表单中添加一个隐藏域,此隐藏于的name属性为:_method如:

        

...
  

   但是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;
	}
	
	@Override
	protected 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;
		}

		@Override
		public String getMethod() {
			return this.method;
		}
	}
	
}

   此类的实现是当使用DELETE协议时请求使用GET然后加上参数_method=DELETE;当使用PUT协议时请求使用POST然后加上_method=PUT

你可能感兴趣的:(java)