最代码官方的gravatar头像
最代码官方 2015-04-07 12:03:35

spring mvc自定义过滤器filter实现对请求参数编解码的代码分享

百度,google了半天即使再万能的stackoverflow上也没有得到解答,今天偶然间发现springmvc注解@RequestParam不是通过HttpServletRequest.java的getParameter(String name)方法得到的参数值,而是通过getParameterValues得到的,怪不得debug了半天getParameter方法就是未被调用,filter也没生效。

相关代码如下:

RequestFilter.java

package com.zuidaima.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

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

import org.springframework.web.filter.OncePerRequestFilter;
/**
*@author www.zuidaima.com
**/
public class RequestFilter extends OncePerRequestFilter {

	public String filter(HttpServletRequest request, String input) {
		String ret = input;
                //ios客户端请求参数值可能为(null)服务端过滤掉当null处理即可
		if (input == null || input.trim().equals("(null)")) {
                        ret=null;
			return ret;
		}
		final String userAgent = request.getHeader("User-Agent");
		final String method = request.getMethod();
                //该处可以实现各种业务的自定义的过滤机制
		if (method.equalsIgnoreCase("get")
				|| userAgent.toLowerCase().indexOf("android") != -1) {
			try {
				ret = new String(input.getBytes("ISO8859-1"), "utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return ret;
	}

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

		chain.doFilter(new HttpServletRequestWrapper(request) {
			@Override
			public String getParameter(String name) {
				String value = super.getParameter(name);
				return filter(this, value);
			}

			@Override
			public String[] getParameterValues(String name) {
				String[] values = super.getParameterValues(name);
				if (values == null) {
					return null;
				}
				for (int i = 0; i < values.length; i++) {
					values[i] = filter(this, values[i]);
				}
				return values;
			}

		}, response);

	}
}

当然必须在web.xml中配置启动该过滤器:

<filter>
		<filter-name>RequestFilter</filter-name>
		<filter-class>com.zuidaima.filter.RequestFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>RequestFilter</filter-name>
		<url-pattern>*.htm</url-pattern>
	</filter-mapping>

这样就可以实现全局的控制springmvc的参数过滤,比如xss,编解码等业务,比在每个springmvc方法中对每个参数值进行判断和过滤简单方便多了。


打赏

顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友