SpringBoot16 之 Listener and Filter
阿新 • • 發佈:2019-01-01
在Springboot的啟動類上必須新增@ServletComponentScan這個標籤,否則不會有效果
@ServletComponentScan作用就是掃描相應的Servlet包;
1、建立一個myFilter類。實現Filter中的方法。
/**
* Created by hua on 2016/12/2.
*/
@WebFilter(filterName="myFilter",urlPatterns="/*")
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("過濾器初始化");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("執行過濾操作");
chain.doFilter(request, response);
}
@Override
public void destroy() {
System.out.println("過濾器銷燬");
}
}
建立Listener
@WebListener
public class MyHttpSessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
System.out.println("Session 被建立");
}
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
System.out.println("ServletContex初始化");
}
}
@WebListener
public class MyServletContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("ServletContex初始化");
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("ServletContex銷燬");
}
}