1、通過web.xml配置Filter
<filter> <filter-name>characterFilter</filter-name> //定義filter名字 <filter-class>filter.characterFilter</filter-class> //定義filter的類 <init-param> //定義初始化參數 使用初始化參數的好處在於:要修改參數值時,可直接通過更改xml文件來修改 <param-name>charset</param-name> //定義初始化參數的名字 <param-value>utf-8</param-value> //定義初始化參數的值 </init-param> </filter> <filter-mapping> //定義filter的映射 <filter-name>characterFilter</filter-name> //定義要映射的名字 <url-pattern>/*</url-pattern> //定義攔截器的范圍 <filter-mapping>
2、通過一個java實現Filter接口來組成攔截器
public class characterFilter implements Filter { //繼承Filter接口 private FilterConfig config; //用來接收初始化參數對象 public void destroy() { //攔截器被銷毀時所調用的函數 } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { //攔截器功能實現的主要函數,每次訪問被攔截的jsp都會調用此函數 String charSet=config.getInitParameter("charset"); //通過初始化參數定義頁面的字符集 request.setCharacterEncoding(charSet); chain.doFilter(request, response); //該函數作用是指向下個攔截器 } public void init(FilterConfig config) throws ServletException { this.config=config; //將xml的初始化參數封裝在成員對象中 } }