セッションリスナーの利用 - JSP

簡単なセッションリスナーの利用方法を紹介します。

コード (usesessionlistener.jsp)

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Hello HttpSessionListener World</title>
  </head>
  <body>
    <h1>Hello HttpSessionListener World</h1>
    <BR><HR><BR>
    <p align="center"><font size="20">Output Session Created Logging!</font></p>
  </body>
</html>

コード (MySessionListerner.java)

package webApplication30;

import javax.servlet.http.*;
import javax.servlet.*;

public class MySessionListener implements HttpSessionListener{
    
    /** Creates a new instance of MySessionListener */
    public MySessionListener() {
    }
    
    public void sessionCreated(HttpSessionEvent se){
        System.out.println("Http Session Object Created!");
    }
    
    public void sessionDestroyed(HttpSessionEvent se){
        System.out.println("Http Session Object Destroyed!");
    }
}

コード (web.xml)

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=
    "http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
  version="2.4">
  <listener>
    <listener-class>webApplication30.MySessionListener</listener-class>
  </listener>
  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

実行結果

Http Session Object Created!

セッションオブジェクトが廃棄されると "Http Session Object Destroyed!" が表示されます。
著者
iPentecのプログラマー、最近はAIの積極的な活用にも取り組み中。
とっても恥ずかしがり。
最終更新日: 2024-01-06
作成日: 2011-02-14
iPentec all rights reserverd.