HiddenHttpMethodFilter源码解析

首先我先给出源码,按着它一点一点分析(当然前面大段的注释和引包我就不要了,想看的同学也可以自己找源码看)

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;
		}
	}

}

首先我们可以看到HiddenHttpMethodFilter它集成了一个叫OncePerRequestFilter的类,我们可以先浏览一下整体代码,很显然的可以发现这个Filter类没有三个方法(生死以及doFilter),那我们就顺着OncePerRequestFilter找,发现OncePerRequestFilter果然有这三个方法,那说明HiddenHttpMethodFilter都是继承了父类的三个方法,那我们接着看。

既然HiddenHttpMethodFilter通常用在RESTful风格里头,多出来的删除和编辑要用put和delete方法,那就需要用_method代替原来的method,接着我们可以从头两句代码可以看出,HiddenHttpMethodFilter先是定义了一个字符串,default_method。那猜都能猜到等会肯定要覆盖这个默认的方法名变成我们的方法名。

当我们接受request(HttpServletRequest)请求时,它会告诉我们它传过来的时“POST”还是“GET”请求,从上面代码可知,我们只有“POST”请求的时候才能根据_method改变method方法名。接着它会帮我们把方法名变成全部大写,然后调用一个HttpMethodRequestWrapper类的构造方法,request依旧不动,但是method变成了我们传进来的参数,也就是我们要改成的方法名。wrapper作为了一个新的HttpServletRequest回到了过滤器链之中。

猜你喜欢

转载自blog.csdn.net/TangXiaoPang/article/details/87858002