본문 바로가기

Servlet/HttpSessionListener

Session 생성 및 종료시 이벤트 처리(사용)

package com.mycompany.listener;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import javax.servlet.http.*

public class SessionListener implements HttpSessionListener {

 @Override
 public void sessionCreated(HttpSessionEvent event) {
  HttpSession ss = event.getSession();
  System.out.println("세션 생성됨");
 }

 @Override
 public void sessionDestroyed(HttpSessionEvent event) {
  HttpSession ss = event.getSession();
  System.out.println("세션 제거됨");
 }
}


Okay, if you add one attribute to the session, the session will be created for you and it should print out “Session is created”. Once you invalidate the session, the session should be destroyed and “Session is destroyed” will be printed out.

Now, we need to add one more entry in our web.xml.

<listener>
<listener-class>com.mycompany.listener.SessionListener</listener-class>
</listener>

One thing you need to know that this listener entry MUST be before the <servlet> entry (if any). So here is my latest web.xml looks like. Yes, Listener only needs <listener></listener>

So this is how my latest web.xml looks like after implementing both ServletContextListener and HttpSessionListener.

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" 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">
<display-name> ListenerWebApp </display-name>
<listener>
<listener-class>com.mycompany.listener.ServletListener</listener-class>
</listener>
<listener>
<listener-class>com.mycompany.listener.SessionListener</listener-class>
</listener>




<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

Ok, actually we have completed our SessionListener. The only thing is that how to test it. There is one thing you can do. Create one JSP on your web application and we will assign some attributes to the sessions (adding attribute means that we are creating the Session). Create your JSP using the wizard and name it whatever you want. For my case, I would like to name it testSession.jsp.

Ok, now let’s add some codes to add attribute to the session. We will achieve it using Scriptlet. Scriptlet is basically Java codes that are embedded in our JSP. It helps us in creating our application dynamic. So please add below codes in your JSP.

참고: 세션객체에 속성을 저장하지 않아도 페이지가 session=true 로 설정되어 있다면 그 페이지에 접속하는 순간 센션객체가 서버에 생성되므로 세션 이벤트가 발생한다. 그러므로 아래의 코드 중에서 setAttribute() 메소드가 실행되지 않아도 세션이벤트(sessionCreated())는 실행된다.

session="false" 으로 설정된 페이지는 해당 페이지에 접속하는 것만으로는 자동으로 세션이 생성되지 않으므로 세션이벤트가 발생하지 않는다. 그러나 session="false" 임에도 불구하고 해당 페이지 내에서 request.getSession().setAttribute("test", "test") 를 이용하여 세션에 속성을 저장하는 경우에는 세션이 생성되면서 세션이벤트가 발생하고 리스너에 등록된 메소드가 실행된다.

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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=EUC-KR">
<title>세션 리스너 테스트 페이지</title>
</head>
<body>
<%
 System.out.println("세션에 속성 추가....");
 request.getSession().setAttribute("test", "test");
 System.out.println("세션에 속성 추가 완료!");

 System.out.println("세션 제거 중....");
 request.getSession().invalidate();
 System.out.println("세션 제거 완료!");
 
 out.println("세션으로부터 속성 추가 및 제거 성공!!!");
%>
</body>
</html>