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中應該配置的東西: <filter> <filter-name>CharactorFilter</filter-name> <filter-class>woniu.struts.filter.CharactorFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharactorFilter</filter-name> <url-pattern>/*</url-pattern>//這裏使用/*,表示在訪問任何頁面時都要經過該過濾器 </filter-mapping>