Java - HTTP Session Example with Listener and Filter

Here we go..

Directory Layout

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/maven-v4_0_0.xsd">
 
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>biz.tugay</groupId>
    <artifactId>sesslist</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
 
    <name>updo Maven Webapp</name>
    <url>http://maven.apache.org</url>
 
    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>3.0.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>
 
    <properties>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
 
    <build>
        <finalName>sesslist</finalName>
        <plugins>
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.2.1.v20140609</version>
            </plugin>
        </plugins>
    </build>
 
</project>

web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
 
    <jsp-config>
        <jsp-property-group>
            <url-pattern>*.jsp</url-pattern>
            <page-encoding>UTF-8</page-encoding>
            <scripting-invalid>true</scripting-invalid>
            <trim-directive-whitespaces>true</trim-directive-whitespaces>
            <default-content-type>text/html;charset=UTF-8</default-content-type>
        </jsp-property-group>
    </jsp-config>
 
</web-app>

SessionRegistry.java
package biz.tugay;
 
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
 
/**
 * User: koraytugay
 * Date: 30/09/14
 * Time: 06:49
 */
public class SessionRegistry {
 
    private static final Map<String, HttpSession> SESSIONS = new Hashtable<>();
 
    //Prevent instantiation
    private SessionRegistry() {
    }
 
    public static void addSession(String sessionId, HttpSession session) {
        SESSIONS.put(sessionId, session);
    }
 
    public static List<HttpSession> getAllSessios() {
        return new ArrayList<>(SESSIONS.values());
    }
}

SessionCreatorFilter.java
package biz.tugay;
 
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
 
/**
 * User: Koray Tugay (koray@tugay.biz)
 * Date: 8/6/2016
 * Time: 7:26 PM
 */
 
@WebFilter(urlPatterns = "/*")
public class SessionCreatorFilter implements Filter {
 
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
 
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        final HttpServletRequest req = (HttpServletRequest) request;
        req.getSession(true);
        chain.doFilter(request, response);
    }
 
    @Override
    public void destroy() {
    }
}

SessionCreatedListener.java
package biz.tugay;
 
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionIdListener;
import javax.servlet.http.HttpSessionListener;
 
/**
 * User: koraytugay
 * Date: 30/09/14
 * Time: 06:43
 */
 
@WebListener(value = "mySessionListener")
public class SessionCreatedListener implements HttpSessionListener, HttpSessionIdListener {
 
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        SessionRegistry.addSession(httpSessionEvent.getSession().getId(), httpSessionEvent.getSession());
    }
 
    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
    }
 
    @Override
    public void sessionIdChanged(HttpSessionEvent httpSessionEvent, String oldSessionId) {
    }
}

SessionListServlet.java
package biz.tugay;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
 
/**
 * User: koraytugay
 * Date: 30/09/14
 * Time: 07:04
 */
 
@WebServlet(urlPatterns = "")
public class SessionListServlet extends HttpServlet {
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setAttribute("allSessions", SessionRegistry.getAllSessios());
        req.getRequestDispatcher("sessions.jsp").forward(req, resp);
    }
}

sessions.jsp
<%--
    User: Koray Tugay (koray@tugay.biz)
    Date: 8/6/2016
    Time: 7:21 PM
--%>
 
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title></title>
</head>
<body>
<div>
    <%--@elvariable id="allSessions" type="java.util.List<javax.servlet.http.HttpSession>"--%>
    <h2>Total number of sessions: ${allSessions.size()}</h2>
</div>
<div>
    <h3>Current sessions</h3>
    <hr/>
    <br/>
    <c:forEach items="${allSessions}" var="session">
        Session id: ${session.id}
        <c:if test="${session.id eq pageContext.session.id}">
            <strong style="margin-left: 10px; font-size: 125%;"> &#x2190; This is you!</strong>
        </c:if>
        <br/>
    </c:forEach>
</div>
</body>
</html>

And in action: