現(xiàn)在來說說Servlet的監(jiān)聽器Listener,它是實(shí)現(xiàn)了javax.servlet.ServletContextListener 接口的服務(wù)器端程序,它也是隨web應(yīng)用的啟動(dòng)
而啟動(dòng),只初始化一次,隨web應(yīng)用的停止而銷毀。主要作用是:做一些初始化的內(nèi)容添加工作、設(shè)置一些基本的內(nèi)容、比如一些參數(shù)或者是一些
固定的對(duì)象等等。首先來看一下ServletContextListener接口的源代碼:
- public abstract interface ServletContextListener extends EventListener{
- public abstract void contextInitialized(ServletContextEvent paramServletContextEvent);
- public abstract void contextDestroyed(ServletContextEvent paramServletContextEvent);
- }
下面利用監(jiān)聽器對(duì)數(shù)據(jù)庫連接池DataSource的初始化演示它的使用:ListenerTest.java
- import javax.servlet.ServletContext;
- import javax.servlet.ServletContextEvent;
- import javax.servlet.ServletContextListener;
- import org.apache.commons.dbcp.BasicDataSource;
- /**
- * 現(xiàn)在來說說Servlet的監(jiān)聽器Listener,它是實(shí)現(xiàn)了javax.servlet.ServletContextListener 接口的
- * 服務(wù)器端程序,它也是隨web應(yīng)用的啟動(dòng)而啟動(dòng),只初始化一次,隨web應(yīng)用的停止而銷毀。主要作用是:做一些初始化
- * 的內(nèi)容添加工作、設(shè)置一些基本的內(nèi)容、比如一些參數(shù)或者是一些固定的對(duì)象等等。
- *
- * 示例代碼:使用監(jiān)聽器對(duì)數(shù)據(jù)庫連接池DataSource進(jìn)行初始化
- */
- public class ListenerTest implements ServletContextListener{
- // 應(yīng)用監(jiān)聽器的銷毀方法
- public void contextDestroyed(ServletContextEvent servletContextEvent) {
- ServletContext servletContext = servletContextEvent.getServletContext();
- // 在整個(gè)web應(yīng)用銷毀之前調(diào)用,將所有應(yīng)用空間所設(shè)置的內(nèi)容清空
- servletContext.removeAttribute("dataSource");
- System.out.println("銷毀工作完成...");
- }
- // 應(yīng)用監(jiān)聽器的初始化方法
- public void contextInitialized(ServletContextEvent servletContextEvent) {
- // 通過這個(gè)事件可以獲取整個(gè)應(yīng)用的空間
- // 在整個(gè)web應(yīng)用下面啟動(dòng)的時(shí)候做一些初始化的內(nèi)容添加工作
- ServletContext servletContext = servletContextEvent.getServletContext();
- // 設(shè)置一些基本的內(nèi)容;比如一些參數(shù)或者是一些固定的對(duì)象
- // 創(chuàng)建DataSource對(duì)象,連接池技術(shù) dbcp
- BasicDataSource basicDataSource = new BasicDataSource();
- basicDataSource.setDriverClassName("com.jdbc.Driver");
- basicDataSource.setUrl("jdbc:mysqlocalhost:3306/");
- basicDataSource.setUsername("root");
- basicDataSource.setPassword("root");
- basicDataSource.setMaxActive(10);//最大連接數(shù)
- basicDataSource.setMaxIdle(5);//最大管理數(shù)
- //bds.setMaxWait(maxWait); 最大等待時(shí)間
- // 把 DataSource 放入ServletContext空間中,
- // 供整個(gè)web應(yīng)用的使用(獲取數(shù)據(jù)庫連接)
- servletContext.setAttribute("dataSource", basicDataSource);
- System.out.println("應(yīng)用監(jiān)聽器初始化工作完成...");
- System.out.println("已經(jīng)創(chuàng)建DataSource...");
- }
- }
web.xml中配置如下,很簡單:
- <!-- 配置應(yīng)用監(jiān)聽器 -->
- <listener>
- <listener-class>com.ycq.ListenerTest</listener-class>
- </listener>
這樣配置好了之后,以后在web應(yīng)用中就可以通過ServletContext取得BasicDataSource對(duì)象,從而獲取與數(shù)據(jù)庫的連接,提高性能,方便使用。
示例代碼二:
- import java.io.File;
- import javax.servlet.ServletContextEvent;
- import javax.servlet.ServletContextListener;
- import com.i2f.fsp.deploy.TransactionDeployer;
- /**
- * 監(jiān)聽器隨著項(xiàng)目的啟動(dòng)而啟動(dòng)
- *
- */
- public class ListenerTest2 implements ServletContextListener{
- // 銷毀監(jiān)聽器
- public void contextDestroyed(ServletContextEvent servletContextEvent) {
- System.out.println("date20161020095500 :" + servletContextEvent.getServletContext());
- }
- public void contextInitialized(ServletContextEvent servletContextEvent) {
- try{
- // 獲取項(xiàng)目跟路徑
- String basePath = servletContextEvent.getServletContext().getRealPath("/");
- // D:\apache-tomcat-6.0.41\webapps\i2money\ 絕對(duì)路徑
- System.out.println("basePath20161020094700 :" + basePath);
- if (!(basePath.endsWith(File.separator))){
- basePath = basePath + File.separator;
- }
- basePath = basePath + "WEB-INF" + File.separator + "classes" + File.separator;
- new TransactionDeployer(basePath).deploy();
- // D:\apache-tomcat-6.0.41\webapps\i2money\WEB-INF\classes\
- System.out.println("basePath20161020094701 :" + basePath);
- }
- catch (Exception e){
- e.printStackTrace();
- System.exit(-1);
- }
- }
- }
示例代碼三:
- import javax.servlet.http.HttpSession;
- import javax.servlet.http.HttpSessionEvent;
- import javax.servlet.http.HttpSessionListener;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import org.springframework.context.ApplicationContext;
- import org.springframework.web.context.support.WebApplicationContextUtils;
- public class UserLogoutListener implements HttpSessionListener{
- protected final Log log = LogFactory.getLog(super.getClass());
- public void sessionCreated(HttpSessionEvent event){
- this.log.error("session created. id = " + event.getSession().getId());
- }
- public void sessionDestroyed(HttpSessionEvent event){
- this.log.error("session destroyed.id = " + event.getSession().getId());
- HttpSession session = event.getSession();
- ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(session.getServletContext());
- OnlineUserMonitorClient client = (OnlineUserMonitorClient)context.getBean("onlineUserMonitorClient");
- client.afterSessionDestroyed(session);
- }
- }
監(jiān)聽器在實(shí)際項(xiàng)目中的應(yīng)用,監(jiān)聽器在java web中應(yīng)用的較多,比如:統(tǒng)計(jì)當(dāng)前在線人數(shù)、自定義session掃描器。
--------------------- 應(yīng)用一:統(tǒng)計(jì)當(dāng)前在線人數(shù) ---------------------
- import javax.servlet.ServletContext;
- import javax.servlet.http.HttpSessionEvent;
- import javax.servlet.http.HttpSessionListener;
- /**
- * @description HttpSessionListener監(jiān)聽器實(shí)現(xiàn)統(tǒng)計(jì)網(wǎng)站在線人數(shù)的功能
- */
- public class SessionListener implements HttpSessionListener{
-
- public static int TOTAL_ONLINE_USERS = 0;
- public void sessionCreated(HttpSessionEvent httpSessionEvent) {
- ServletContext servletContext = httpSessionEvent.getSession().getServletContext();
- TOTAL_ONLINE_USERS = (Integer) servletContext.getAttribute("TOTAL_ONLINE_USERS");
- // 如果用戶退出,TOTAL_ONLINE_USERS自減1
- if(TOTAL_ONLINE_USERS == 0){
- servletContext.setAttribute("TOTAL_ONLINE_USERS", 1);
- }
- else{
- TOTAL_ONLINE_USERS--;
- servletContext.setAttribute("TOTAL_ONLINE_USERS", TOTAL_ONLINE_USERS);
- }
- }
-
- public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
- ServletContext servletContext = httpSessionEvent.getSession().getServletContext();
- TOTAL_ONLINE_USERS = (Integer) servletContext.getAttribute("TOTAL_ONLINE_USERS");
- // 如果用戶登錄,TOTAL_ONLINE_USERS自增1
- if(TOTAL_ONLINE_USERS == 0){
- servletContext.setAttribute("TOTAL_ONLINE_USERS", 1);
- }
- else{
- TOTAL_ONLINE_USERS++;
- servletContext.setAttribute("TOTAL_ONLINE_USERS", TOTAL_ONLINE_USERS);
- }
- }
- }
--------------------- 應(yīng)用二:自定義session掃描器 ---------------------
- import java.util.LinkedList;
- import java.util.List;
- import java.util.Timer;
- import javax.servlet.ServletContextEvent;
- import javax.servlet.ServletContextListener;
- import javax.servlet.http.HttpSession;
- import javax.servlet.http.HttpSessionEvent;
- import javax.servlet.http.HttpSessionListener;
- import jeus.util.concurrent50.Collections;
- /**
- * @description 當(dāng)網(wǎng)站用戶量增加時(shí),session占用的內(nèi)存會(huì)越來越大,這時(shí)session的管理,將會(huì)是一項(xiàng)很大的
- * 系統(tǒng)開銷,為了高效的管理session,我們可以寫一個(gè)監(jiān)聽器,定期清理掉過期的session
- */
- public class SessionScanerListener implements HttpSessionListener,ServletContextListener{
- // 創(chuàng)建一個(gè)線程安全的集合,用來存儲(chǔ)session
- @SuppressWarnings("unchecked")
- List<HttpSession> sessionList = Collections.synchronizedList(new LinkedList<HttpSession>());
- private Object lock = new Object();
-
- public void sessionCreated(HttpSessionEvent httpSessionEvent) {
- System.out.println("session 創(chuàng)建成功...");
- HttpSession httpSession = httpSessionEvent.getSession();
- synchronized (lock){
- sessionList.add(httpSession);
- }
- }
-
- public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
- System.out.println("session 銷毀成功...");
- }
- // web應(yīng)用關(guān)閉時(shí)觸發(fā)contextDestroyed事件
- public void contextDestroyed(ServletContextEvent servletContextEvent) {
- System.out.println("web應(yīng)用關(guān)閉...");
- }
-
- // web應(yīng)用啟動(dòng)時(shí)觸發(fā)contextInitialized事件
- public void contextInitialized(ServletContextEvent servletContextEvent) {
- System.out.println("web應(yīng)用初始化...");
- // 創(chuàng)建定時(shí)器
- Timer timer = new Timer();
- // 每隔30秒就定時(shí)執(zhí)行任務(wù)
- timer.schedule(new MyTask(sessionList,lock), 0, 1000*30);
- }
- }
- import java.util.List;
- import java.util.ListIterator;
- import java.util.TimerTask;
- import javax.servlet.http.HttpSession;
- /**
- * 定時(shí)器,定義定時(shí)任務(wù)的具體內(nèi)容
- */
- public class MyTask extends TimerTask{
- private List<HttpSession> list;
- // 存儲(chǔ)傳遞過來的鎖
- private Object lock;
- // 構(gòu)造方法
- MyTask(List<HttpSession> list, Object lock){
- this.list = list;
- this.lock = lock;
- }
- @Override
- public void run() {
- // 考慮到多線程的情況,這里必須要同步
- synchronized (lock){
- System.out.println("定時(shí)器開始執(zhí)行...");
- ListIterator<HttpSession> listIterator = list.listIterator();
- while(listIterator.hasNext()){
- HttpSession httpSession = listIterator.next();
- // httpSession.getLastAccessedTime() = session的最后訪問時(shí)間
- if(System.currentTimeMillis() - httpSession.getLastAccessedTime() > 1000*30){
- // 手動(dòng)銷毀session
- httpSession.invalidate();
- // 從集合中移除已經(jīng)被銷毀的session
- listIterator.remove();
- }
- }
- }
- }
- }
|