`

SpringMVC杂记(九) 模拟其他类型(非GET,POST)的请求

 
阅读更多
1) 以前一个小兄弟问我,SpringMVC是否可以使用很多浏览器不支持的(DELETE, HEAD等)请求。
我依稀记得有个Filter可以把请求模拟成Delete方式。我直接回答说org.springframework.web.filter.HiddenHttpMethodFilter可以干这个事情。

2) 今日偶尔看到这个类的源代码发现根本不是如此。它只能将POST请求转换为其他请求。
if ("POST".equals(request.getMethod()) && StringUtils.hasLength(paramValue)) {// 只转换POST求情
	String method = paramValue.toUpperCase(Locale.ENGLISH);
	HttpServletRequest wrapper = new HttpMethodRequestWrapper(request, method);
	filterChain.doFilter(wrapper, response);
}

看来以后回答别人的问题还是应该自己先查文档或者看一看源代码,要不然很有可能要出错的。

3) 为了让所有请求都可以模拟成DELETE等请求,只有自己写一个Filter实现和一个HttpServletRequest的装饰器
import java.io.IOException;
import java.util.Locale;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.Assert;
import org.springframework.web.filter.OncePerRequestFilter;

public class HttpMethodSupportFilter extends OncePerRequestFilter {
	
	public static final String DEFAULT_METHOD_PARAM = "_method";

	private String methodParam = DEFAULT_METHOD_PARAM;

	@Override
	protected void doFilterInternal(
			HttpServletRequest request,
			HttpServletResponse response, 
			FilterChain filterChain) throws ServletException, IOException {

		String parameterValue = request.getParameter(methodParam);
		
		if (parameterValue != null) {
			String method = parameterValue.toUpperCase(Locale.ENGLISH);
			System.out.println(method);
			filterChain.doFilter(new HttpServletRequestWrapper(request, method), response);
		}
		else {
			filterChain.doFilter(request, response);
		}
	}

	public void setMethodParam(String methodParam) {
		Assert.hasLength(methodParam);
		this.methodParam = methodParam;
	}

	// Servlet装饰器
	private static class HttpServletRequestWrapper extends javax.servlet.http.HttpServletRequestWrapper {

		private String method;

		public HttpServletRequestWrapper(HttpServletRequest request, String method) {
			super(request);
			this.method = method;
		}

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

	}
}


4) 最后一点,如果使用Form提交模拟DELETE请求等时候,要注意到Form是否有文件上传,如果有的话,也不能忘记把
org.springframework.web.multipart.support.MultipartFilter
配置在HttpMethodSupportFilter前面。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics