前面都说到了springboot中应用servlet和filter,本文继续说springboot应用监听器Listener,大体上是和之前差不多的应用。

实现HttpSessionListener接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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

1
2
3
4
5
@WebListener
public class MyHttpSessionListener implements HttpSessionListener {...}

@WebListener
public class MyServletContextListener implements ServletContextListener {...}

2.然后在启动类中增加@ServletComponentScan,使项目中的Listener能够被扫描到

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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初始化>>>>>>>>>