import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletException;
import javax.servlet.FilterConfig;
public class EncodingFilter implements Filter {
protected FilterConfig filterConfig;
private String targetEncoding = "gb2312";
public void init(FilterConfig config) throws ServletException {
this.filterConfig = config;
this.targetEncoding = config.getInitParameter("encoding");
}
public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain chain)
throws IOException, ServletException {
//System.out.println("使用以下方法对请求进行编码:encoding="+targetEncoding);
HttpServletRequest request = (HttpServletRequest)srequest;
request.setCharacterEncoding(targetEncoding);
chain.doFilter(srequest,sresponse);
}
public void setFilterConfig(final FilterConfig filterConfig)
{
this.filterConfig=filterConfig;
}
public void destroy()
{
this.filterConfig=null;
}
}
在WEB-INF/web.xml下面配置
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>com.david.common.sys.EncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>gb2312</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>