解答例 - 実習課題3 - 8.リスナー2
(実習課題3)
任意のWebアプリケーションにHttpSessionActivationListenerを実装したオブジェクトを追加し、HttpSessionActivationListenerが動作するタイミングを確認すること。
解答例
/* * CountBean.java TECHSCORE Java Servlet8章 実習課題3 * * Copyright (c) 2004 Four-Dimensional Data, Inc. */ package com.techscore.servlet.chapter8.exercise3; import java.io.Serializable; import javax.servlet.http.HttpSessionActivationListener; import javax.servlet.http.HttpSessionEvent; public class CountBean implements HttpSessionActivationListener, Serializable { private int count = 0; public String toString(String functionName) { return new String("Servlet8-3 " + functionName + "\tcount=" + count); } synchronized public void increase() { count++; } synchronized public void decrease() { count--; } public int getCount() { return count; } public void sessionDidActivate(HttpSessionEvent event) { event.getSession().getServletContext().log( toString("sessionDidActivate()")); } public void sessionWillPassivate(HttpSessionEvent event) { event.getSession().getServletContext().log( toString("sessionWillPassivate()")); } }
/* * UserCountListener.java TECHSCORE Java Servlet8章 実習課題3 * * Copyright (c) 2004 Four-Dimensional Data, Inc. */ package com.techscore.servlet.chapter8.exercise3; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class UserCountListener implements HttpSessionListener { private CountBean count = new CountBean(); public void sessionCreated(HttpSessionEvent event) { count.increase(); event.getSession().setAttribute("userCount3", count); } public void sessionDestroyed(HttpSessionEvent event) { count.decrease(); } }
/* * UserCountListener.java TECHSCORE Java Servlet8章 実習課題3 * * Copyright (c) 2004 Four-Dimensional Data, Inc. */ package com.techscore.servlet.chapter8.exercise3; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class UserCountListener implements HttpSessionListener { private CountBean count = new CountBean(); public void sessionCreated(HttpSessionEvent event) { count.increase(); event.getSession().setAttribute("userCount3", count); } public void sessionDestroyed(HttpSessionEvent event) { count.decrease(); } }