基于4.1.7.RELEASE
就如同它的名字,该类负责解析隐藏的HttpMethod,用了这个Filter之后,你可以在页面上POST时指定_method参数,该Filter会根据参数指定的值将Request包装成为指定的HttpMethod的request。需要注意的有两点
1 必须是POST方式才进行处理
2 可以通过设置methodParam来更改参数名字,默认为_method。
主要代码如下
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);
}
}
根据注意事项1,如果是GET则直接进行下一个Filter处理。如果是POST,_method参数所传递进来的所有值都会被转换为大写。
附包装器代码
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;
}
}