JSP - SPLessons

JSP Hits Counter

Chapter 25

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

JSP Hits Counter

JSP Hits Counter

shape Description

JSP Hits Counter – Generally, after publishing any web site, the owner of the website will check how the website is getting popular by seeing the views, these views will come with hits counter. getAttribute () and setAttribute are the methods will be used in hits counter concept. Even though if refresh the application counting will be increased per each refresh or reloading, when restart the server application count will be shown as 1. Following is the syntax to set a variable.

application.setAttribute(String Key, Object Value);

Following is the syntax to get the variable.

application.getAttribute(String Key);

shape Example

Following is an example for JSP Hits Counter, here used setAttribute and getAttribute methods.

<%@ page import="java.io.*,java.util.*" %>
<title>Applcation object in JSP</title>
<body bgcolor="skyblue">
<img src="E:/splessons.png"></br>
<a href="https://www.splessons.com">Splessons.com</a></br>
    Integer hitsCount = 
    if( hitsCount ==null || hitsCount == 0 ){
       /* First visit */
       out.println("Welcome to SPlessons");
       hitsCount = 1;
       /* return visit */
       out.println("Welcome back to SPlessons!");
       hitsCount += 1;
    application.setAttribute("hitCounter", hitsCount);
<p>Total number of visits: <%= hitsCount%></p>

JSP Hits Counter – At the point when call this JSP page utilizing URL http://localhost:8080/index.jsp. This would show hit counter esteem which would build each time when you invigorate the page. one can attempt to get to the page utilizing distinctive browsers and the designer will observe that hit counter will continue expanding with each hit and would show come about something as follows.

When the developer restart the web server, this will reset your application variable and your counter will reset to zero. To stay away from this misfortune, one can actualize your counter in expert way which is as per the following.


shape Key Points

  • setAttribute is the method to set the variable in application.
  • JSP Hits Counter – getAttribute is the method to get the variable.