前面都说到了springboot中应用servlet和filter,本文继续说springboot应用监听器Listener,大体上是和之前差不多的应用。
一.HttpSessionListener
package com.maxbill.core.webbox.listener;
/** * @功能 * @作者 zuoshuai(MaxBill) * @日期 2017/7/6 * @时间 15:27 * @备注 MyHttpSessionListener */
import org.apache.log4j.Logger;
import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener;
@WebListener public class MyHttpSessionListener implements HttpSessionListener {
Logger log = Logger.getLogger(MyServletContextListener.class);
@Override
public void sessionCreated(HttpSessionEvent se) {
log.info(">>>>>>>>>session被创建>>>>>>>>>");
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
log.info(">>>>>>>>session被销毁>>>>>>>>>");
}
}
二.ServletContextListener
package com.maxbill.core.webbox.listener;
import com.maxbill.core.webbox.filter.MyFilter; import org.apache.log4j.Logger;
import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener;
/** * @功能 自定义监听器 * @作者 zuoshuai(MaxBill) * @日期 2017/7/6 * @时间 15:24 * @备注 MyServletContextListener */ @WebListener public class MyServletContextListener implements ServletContextListener {
Logger log = Logger.getLogger(MyServletContextListener.class);
@Override
public void contextInitialized(ServletContextEvent arg) {
log.info(">>>>>>>>>ServletContex初始化>>>>>>>>>");
}
@Override
public void contextDestroyed(ServletContextEvent arg) {
log.info(">>>>>>>>>ServletContex销毁>>>>>>>>>");
}
}
三.增加注解
1.在监听器上增加@WebListener
@WebListener public class MyHttpSessionListener implements HttpSessionListener {...}
@WebListener public class MyServletContextListener implements ServletContextListener {...}
2.然后在启动类中增加@ServletComponentScan,使项目中的Listener能够被扫描到
package com.maxbill;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan;
@ServletComponentScan @SpringBootApplication public class MaxbillApplication {
public static void main(String\[\] args) {
SpringApplication.run(MaxbillApplication.class, args);
}
}
启动项目测试:
INFO com.maxbill.core.webbox.listener.MyServletContextListener:24 - >>>>>>>>>ServletContex初始化>>>>>>>>>