package woniu.struts.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;//统一编码的过滤器public class CharactorFilter implements Filter { private String encoding=null;//编码格式//将encoding设置为null @Override public void destroy() { // TODO Auto-generated method stub encoding=null; } //将得到的encoding进行编码 @Override public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { // TODO Auto-generated method stub if(encoding!=null) { arg0.setCharacterEncoding(encoding); arg1.setContentType("text/html;charset="+encoding); } arg2.doFilter(arg0, arg1);//通过过滤器链arg2将进入下一个过滤器或者直接到页面显示 }//初始化操作,从配置文件中拿到初始化数据 @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub encoding=arg0.getInitParameter("encoding"); }
在web.xml中应该配置的东西:CharactorFilter woniu.struts.filter.CharactorFilter encoding UTF-8 CharactorFilter /* //这里使用/*,表示在访问任何页面时都要通过该过滤器