Filter定義:
public class EncodingFilter implements Filter {
/**
* Default constructor.
*/
public EncodingFilter()
{
System.out.println("創建過濾器EncodingFilter");
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
System.out.println("filter destroy");
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
// place your code here
HttpServletRequest httpReq = (HttpServletRequest)request;
System.out.println("call Encoding doFilter,requestURI:" + httpReq.getRequestURI());
response.setContentType("text/html; charset=UTF-8");
// pass the request along the filter chain
chain.doFilter(request, response);
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
System.out.println("Encoding Filter init,config:" + fConfig);
}
Filter配置:
encodingFilter
filter.EncodingFilter
encodingFilter
/login.jsp
啟動容器時,打印結果如下:
創建過濾器EncodingFilter
Encoding Filter init,config:ApplicationFilterConfig[name=encodingFilter, filterClass=filter.EncodingFilter]
創建過濾器EncodingFilter
Encoding Filter init,config:ApplicationFilterConfig[name=filter.EncodingFilter, filterClass=filter.EncodingFilter]
從打印信息來看,是執行了兩次init。根據debug,進一步證實。
疑問是,既然filter配置的是同一個過濾器,那麼為什麼初始化時要調用兩次呢?而且兩次的fitername不一樣。
求解。
你是配置了兩個過濾器的,只是過濾器的類型是同一個。
容器啟動過程中是根據你配置的filter節點創建過濾器的,你配置了兩個名稱不同但類型相同的過濾器,那它就會實例化兩個過濾器了。
祝好!