Counting Access Times by IP

JavaJavaBeginner
Practice Now

Introduction

In this project, you will learn how to build a simple IP visitor tracking application using Java Servlet and JSP. The application will keep track of the IP addresses of visitors accessing the website and the number of times each IP address has visited.

Preview

project preview

🎯 Tasks

In this project, you will learn:

  • How to implement the index.jsp file to display the IP addresses and their visit counts.
  • How to implement the MyListener class to create and store the ipVisitMap in the ServletContext.
  • How to implement the MyFilter class to count the number of visits for each IP address and update the ipVisitMap.

🏆 Achievements

After completing this project, you will be able to:

  • Build a simple web application using Java Servlet and JSP.
  • Use the ServletContext to store and retrieve application-level data.
  • Use a Filter to intercept and process incoming requests.
  • Use synchronization to ensure thread-safe access to shared resources.

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) html(("`HTML`")) -.-> html/FormsandInputGroup(["`Forms and Input`"]) java/ObjectOrientedandAdvancedConceptsGroup -.-> java/annotation("`Annotation`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/hashmap("`HashMap`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") html/FormsandInputGroup -.-> html/forms("`Form Elements`") subgraph Lab Skills java/annotation -.-> lab-300352{{"`Counting Access Times by IP`"}} java/hashmap -.-> lab-300352{{"`Counting Access Times by IP`"}} java/oop -.-> lab-300352{{"`Counting Access Times by IP`"}} html/forms -.-> lab-300352{{"`Counting Access Times by IP`"}} end

Implement the index.jsp File

In this step, you will learn how to implement the index.jsp file to display the IP addresses and their visit counts.

  1. Open the index.jsp file located in the /home/labex/project/IpProject/src/main/webapp directory.

  2. Add the following code to the index.jsp file:

<%@ page import="java.util.Map" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>IP Visitor Tracker</title>
</head>
<body>
<h1>IP Visitor Tracker</h1>
<table border="1">
    <tr>
        <th>IP Address</th>
        <th>Visit Count</th>
    </tr>
    <%
        Map<String, Integer> ipVisitMap = (Map<String, Integer>) getServletContext().getAttribute("ipVisitMap");
        if (ipVisitMap != null) {
            for (String ip : ipVisitMap.keySet()) {
    %>
    <tr>
        <td><%= ip %></td>
        <td><%= ipVisitMap.get(ip) %></td>
    </tr>
    <%
            }
        }
    %>
</table>
</body>
</html>

This code retrieves the ipVisitMap from the ServletContext and displays the IP addresses and their visit counts in a table.

Implement the MyListener Class

In this step, you will learn how to implement the MyListener class to create and store the ipVisitMap in the ServletContext.

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

  2. Add the following code to the MyListener class:

package org.labex.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.HashMap;
import java.util.Map;

@WebListener
public class MyListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();
        Map<String, Integer> ipVisitMap = new HashMap<>();
        servletContext.setAttribute("ipVisitMap", ipVisitMap);
    }

    public void contextDestroyed(ServletContextEvent sce) {
        // Cleanup code if needed
    }
}

This code creates a new HashMap called ipVisitMap to store the IP addresses and their visit counts, and then sets it as an attribute of the ServletContext.

Implement the MyFilter Class

In this step, you will learn how to implement the MyFilter class to count the number of visits for each IP address and update the ipVisitMap.

  1. Open the MyFilter.java file located in the /home/labex/project/IpProject/src/main/java/org/labex/filter directory.

  2. Add the following code to the MyFilter class:

package org.labex.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

@WebFilter("/*")
public class MyFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {
        // Initialization code if needed
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String ipAddress = httpRequest.getRemoteAddr();
        ServletContext servletContext = httpRequest.getServletContext();
        Map<String, Integer> ipVisitMap = (Map<String, Integer>) servletContext.getAttribute("ipVisitMap");

        synchronized (ipVisitMap) {
            if (ipVisitMap.containsKey(ipAddress)) {
                ipVisitMap.put(ipAddress, ipVisitMap.get(ipAddress) + 1);
            } else {
                ipVisitMap.put(ipAddress, 1);
            }
        }

        chain.doFilter(request, response);
    }

    public void destroy() {
        // Cleanup code if needed
    }
}

This code retrieves the ipVisitMap from the ServletContext, gets the IP address of the current client, and then updates the ipVisitMap accordingly. The synchronized block ensures that the updates to the ipVisitMap are thread-safe.

Test the Application

  1. Open a terminal and navigate to the /home/labex/project/IpProject directory.

  2. Start the Tomcat server by running the following command:

mvn tomcat7:run
  1. Open a web browser and navigate to http://127.0.0.1:8080. You should see the IP Visitor Tracker page with the IP addresses and their visit counts.

  2. Refresh the page several times to see the visit counts increase.

project result

Summary

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

Other Java Tutorials you may like