Ruang penulis
← Kembali ke jurnal
Servlet

How do I capture session creation and removal events?

The Servlet specification define an HttpSessionListener interface that can be implemented if we want to listen to session creation and removal events. The interface has two methods that we can implement, the sessionCreated(HttpSessionEvent event) and sessionDestroyed(HttpSessionEvent event) methods. To activate the listener we need to register it in the servlet container. To register the listener […]

DWayan · 19 Jun 2007 · 2 menit baca

Artikel oleh Wayan · Sumber: Kode Java ↗

Terjemahan artikel ini belum tersedia. Isi asli ditampilkan.

The Servlet specification define an HttpSessionListener interface that can be implemented if we want to listen to session creation and removal events. The interface has two methods that we can implement, the sessionCreated(HttpSessionEvent event) and sessionDestroyed(HttpSessionEvent event) methods. To activate the listener we need to register it in the servlet container. To register the listener we can use the @WebListener annotation. Let’s see the full code snippet below.

package org.kodejava.servlet;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.Date;

@WebListener
public class MySessionListener implements HttpSessionListener {

    // Notification that a new session was created
    @Override
    public void sessionCreated(HttpSessionEvent event) {
        HttpSession session = event.getSession();

        System.out.println("New session created  : " + session.getId());
        System.out.println("Session creation time: " + new Date(session.getCreationTime()));
    }

    // Notification that a session was invalidated
    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        HttpSession session = event.getSession();

        System.out.println("Session destroyed  : " + session.getId());
    }
}

Maven dependencies

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

Maven Central

← Jelajahi catatan lainnya