import java.io.IOException; import java.util.Collections;import java.util.Enumeration;import java.util.HashMap;import java.util.Map;import javax.servlet.Filter; import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequestWrapper;import javax.servlet.http.HttpServletResponse;import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;@SuppressWarnings("unchecked") public class GetQueryStringEncoding implements Filter {private static final Log logger = LogFactory .getLog(GetQueryStringEncoding.class);public void destroy() { }public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpServletRequest httpReq = (HttpServletRequest) request;HttpServletResponse httpResp = (HttpServletResponse) response;httpReq.setCharacterEncoding("UTF-8");httpResp.setCharacterEncoding("UTF-8");if (httpReq.getQueryString() != null && httpReq.getMethod().equalsIgnoreCase("get")) { if (logger.isDebugEnabled())logger.debug("Intercept Query String: "+ httpReq.getQueryString());final MapparameterMap = new HashMap ();Enumeration paramNames = httpReq.getParameterNames();while (paramNames.hasMoreElements()) {String paramName = (String) paramNames.nextElement();String[] values = httpReq.getParameterValues(paramName);for (int i = 0; i < values.length; i++) {if (values[i] != null)values[i] = new String(values[i].getBytes("ISO-8859-1"), "UTF-8");}parameterMap.put(paramName, values);}chain.doFilter(new HttpServletRequestWrapper(httpReq) {@Override public String getParameter(String name) {if (parameterMap.get(name) == null)return null;return parameterMap.get(name)[0];}@Override public Map getParameterMap() {return parameterMap;}@Override public Enumeration getParameterNames() {return Collections.enumeration(parameterMap.keySet());}@Override public String[] getParameterValues(String name) {return parameterMap.get(name);}}, response); } else {chain.doFilter(request, response);}} public void init(FilterConfig fConfig) throws ServletException { if (logger.isInfoEnabled())logger.info("GetQueryStringEncoding Filter install...");}}
红色部分不是来自原文,是我新加的。