web.xml加載順序
1.先加載<context-param>標籤
2.創建servletContext容器
3.把<context-parame>標籤中數據轉化成鍵值樹交給servletContext容器
4.創建Listener實例
5.加載filter(過濾器)
6.加載Interceptor(攔截器)
7.加載servlet
注:filter加載順序:根據web.xml中<filter-mapper>來決定 servlet一樣如此
1.自定義Listener,我們需要實現ServletContextListener接口
public class MyListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
//加上自己的處理邏輯
}
public void contextDestroyed(ServletContextEvent event) {
//銷燬時 處理邏輯
}
}
2.自定義filter,需要實現filter接口
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response =(HttpServletResponse) res;
//攔截業務邏輯
// 將控制權傳遞到下一個過濾器
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
3.自定義Interceptor,需要實現HandlerInterceptor接口 或者繼承 HandlerInterceptorAdapter
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,Exception arg3) throws Exception {
// TODO Auto-generated method stub
}
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,ModelAndView arg3) throws Exception {
// TODO Auto-generated method stub
}
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
//攔截邏輯 通過返回 true; 不通過返回false;
}