Skip to main content

Blarg #21: DevelopMentor JWT links that need to be on-line

Posted by jfalkner on March 20, 2006 at 10:08 AM PST

For those of you at DevelopMentor's Java Web Tier course, here are the links we used in class. If you weren't at this class and you want to learn about making websites with Java.... Ha, I bet DM loves me now!

Here are those links.

This class counts the number of current sessions. When one is created, the count goes up. When one is destroyed, the count goes down. This is not a hit tracker. It is a count of "live" users.

package example;

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

*A listener class that counts the number of concurent sessions.
* @author Jayson Falkner -
public class SessionCountListener implements HttpSessionListener {
    int count = 0;
     *When a session is destroyed, decrement the counter.
    public void sessionDestroyed(HttpSessionEvent se) {
        // increment the count
        // set the attribute
     *When a session is created, increment the counter.
    public void sessionCreated(HttpSessionEvent se) {
        // decrement the count
        // set the attribute
    // helper method to set the attribte in 'application' scope
    private void setAttribute(HttpSessionEvent se) {
        // get the session
        HttpSession hs = se.getSession();
        // get the servlet context
        ServletContext sc = hs.getServletContext();
        // set the attribute on the servlet context
        sc.setAttribute("userCount", Integer.toString(count));

And don't forget that you must register this class via web.xml

    <!-- rest of your web.xml stuff... -->

Finally, you can show the count from any JSP or serlvet that has access to the ServletContext object. Here is an example JSP.

    <h1>JSP Page ${userCount}</h1>