Recording Web Page Accesses Using Listeners

JavaJavaBeginner
Practice Now

Introduction

In this project, you will learn how to implement a web page access tracking functionality using a listener. The goal of this project is to create a web application that can display the number of users currently accessing the home page.

👀 Preview

result

🎯 Tasks

In this project, you will learn:

  • How to implement the MyListener.java class to track the number of hits to the home page.
  • How to implement the index.jsp file to display the current visitors count.
  • How to configure the MyListener in the web.xml file.
  • How to start the Tomcat server and test the application.

🏆 Achievements

After completing this project, you will be able to:

  • Use the HttpSessionListener interface to track user sessions.
  • Store and retrieve the visitors count in the ServletContext.
  • Display the visitors count in a JSP file.
  • Configure a listener in the web.xml file.
  • Start and test a web application using Tomcat.

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ConcurrentandNetworkProgrammingGroup(["`Concurrent and Network Programming`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java/ConcurrentandNetworkProgrammingGroup -.-> java/net("`Net`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/interface("`Interface`") java/ConcurrentandNetworkProgrammingGroup -.-> java/working("`Working`") subgraph Lab Skills java/net -.-> lab-300394{{"`Recording Web Page Accesses Using Listeners`"}} java/class_methods -.-> lab-300394{{"`Recording Web Page Accesses Using Listeners`"}} java/interface -.-> lab-300394{{"`Recording Web Page Accesses Using Listeners`"}} java/working -.-> lab-300394{{"`Recording Web Page Accesses Using Listeners`"}} end

Implement the MyListener.java Class

In this step, you will learn how to implement the MyListener.java class to track the number of hits to the home page.

  1. Open the MyListener.java file located in the ListenerProject/src/main/java/org/labex/listener directory.

  2. Implement the MyListener class, which implements the HttpSessionListener interface. This interface provides two methods: sessionCreated() and sessionDestroyed().

  3. In the sessionCreated() method, do the following:

    • Get the ServletContext from the HttpSessionEvent object.
    • Retrieve the "count" attribute from the ServletContext. If the attribute is null, initialize it to 1. Otherwise, increment the count by 1.
    • Set the updated "count" attribute back to the ServletContext.
  4. In the sessionDestroyed() method, do the following:

    • Get the ServletContext from the HttpSessionEvent object.
    • Retrieve the "count" attribute from the ServletContext. If the count is greater than 0, decrement the count by 1.
    • Set the updated "count" attribute back to the ServletContext.

Your MyListener.java class should look like this:

package org.labex.listener;

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

public class MyListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext context = se.getSession().getServletContext();
        Integer count = (Integer) context.getAttribute("count");

        if (count == null) {
            count = 1;
        } else {
            count++;
        }

        context.setAttribute("count", count);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext context = se.getSession().getServletContext();
        Integer count = (Integer) context.getAttribute("count");

        if (count != null && count > 0) {
            count--;
        }

        context.setAttribute("count", count);
    }
}

Implement the index.jsp File

In this step, you will learn how to implement the index.jsp file to display the number of hits to the home page.

  1. Open the index.jsp file located in the ListenerProject/src/main/webapp directory.

  2. In the JSP file, import the necessary classes:

    • javax.servlet.ServletContext
    • javax.servlet.http.HttpServletRequest
  3. Implement a method called getVisitorsCount() that takes an HttpServletRequest object as a parameter. In this method, do the following:

    • Get the ServletContext from the HttpServletRequest object.
    • Retrieve the "count" attribute from the ServletContext. If the attribute is null, return 0. Otherwise, return the count value.
  4. In the JSP file, display the current visitors count by calling the getVisitorsCount() method and embedding the result in the HTML.

Your index.jsp file should look like this:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%> <%@ page import="javax.servlet.ServletContext" %> <%@
page import="javax.servlet.http.HttpServletRequest" %>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Index Page</title>
  </head>
  <body>
    <%! public int getVisitorsCount(HttpServletRequest request) { ServletContext
    context = request.getServletContext(); Integer count = (Integer)
    context.getAttribute("count"); return (count != null) ? count : 0; } %>

    <h1>Welcome to My Website</h1>
    <p>Current Visitors: <%= getVisitorsCount(request) %></p>
  </body>
</html>

Configure the Listener in web.xml

In this step, you will learn how to configure the MyListener in the web.xml file.

  1. Open the web.xml file located in the ListenerProject/src/main/webapp/WEB-INF directory.

  2. Add the following configuration to the web.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<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_4_0.xsd"
         version="4.0">

    <!-- Define your listener -->
    <listener>
        <listener-class>org.labex.listener.MyListener</listener-class>
    </listener>

</web-app>

This configuration will register the MyListener class as a listener in the web application.

Start the Tomcat Server and Test the Application

  1. Open a terminal and navigate to the ListenerProject directory using the following command:

    cd ~/project/ListenerProject/
  2. Start the Tomcat server using the following command:

    mvn clean tomcat7:run
  3. Open a web browser and go to http://localhost:8080. You should see the "Welcome to My Website" page with the current visitors count displayed.

  4. Refresh the page a few times, and you should see the visitors count increasing.

  5. Close the browser and wait a few minutes. Refresh the page again, and you should see the visitors count decreasing.

Congratulations! You have successfully implemented the web page access tracking functionality using a listener.

Summary

Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.

Other Java Tutorials you may like