request编码Filter

package com.filter;

import java.io.IOException;
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;

/**
 * 前端设置request编码
 * @
 */
public class EncodingFilter implements Filter
{
	static org.apache.log4j.Logger logger=Logger.getLogger(EncodingFilter.class);

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	public void init(FilterConfig pArg0) throws ServletException
	{
	}

	public void doFilter(ServletRequest pRequest,ServletResponse response,FilterChain pArg2) throws IOException,ServletException
	{
		logger.info("前端设置request编码");
		HttpServletRequest request=(HttpServletRequest)pRequest;
		String queryString=request.getQueryString();
		String encoding=getParameter(queryString,SYSConstant.ENCODING_PARAM_NAME);
		if(encoding==null)
		{
			encoding="UTF-8";
		}

		pRequest.setCharacterEncoding(encoding);
		logger.debug("encoding:"+encoding);
		pArg2.doFilter(request,response);
	}
	/**
	 * 从request中读出param的值,不考虑编码问题
	 * @param request
	 * @param pParamName
	 * @param pEncoding
	 * @return
	 */
	public String getParameter(String queryString,String pParamName)
	{
		logger.info("从request中读出param的值,不考虑编码问题");
		String[] paramPairs=StringHelper.split(queryString, '&');
		for(int i=0;i<paramPairs.length;i++)
		{
			int indexEquals=paramPairs[i].indexOf('=');
			if(indexEquals!=-1)
			{
				String name=paramPairs[i].substring(0,indexEquals);
				if(name.equalsIgnoreCase(pParamName))
				{
					String value=paramPairs[i].substring(indexEquals+1);
					return value;
				}
			}
		}
		return null;
	}
	/* (non-Javadoc)
	 * @see javax.servlet.Filter#destroy()
	 */
	public void destroy()
	{
	}

}

你可能感兴趣的:(java,servlet,filter)