Count number of visitors on website - JSP

Q. Write a JSP application to count the total number of visits on your website.

Answer:

Page counter means the number of times the page has been visited by the users.

Below example shows how to count total number of hit on the particular page.

count-visitor.jsp

<%@ page import="java.io.*,java.util.*" %>
<html>
    <head>
        <title>Count visitor</title>
    </head>
    <body>
        <form>
            <fieldset style="width:20%; background-color:#e6ffe6;">
                <legend>Count visitor</legend>
                <%
                    Integer hitsCount =
                    (Integer)application.getAttribute("hitCounter");
                    if( hitsCount ==null || hitsCount == 0 )
                    {
                        /* First visit */
                        out.println("Welcome to my website!!");
                        hitsCount = 1;
                    }
                    else
                    {
                        /* return visit */
                        out.println("Welcome to my website!!");
                        hitsCount += 1;
                    }
                    application.setAttribute("hitCounter", hitsCount);
                %>
                <p>You are visitor number: <%= hitsCount%></p>
            </fieldset>
        </form>
    </body>
</html>


web.xml

<web-app>
    <servlet>
        <servlet-name>xyz</servlet-name>
        <jsp-file>/count-visitor.jsp</jsp-file>
    </servlet>
    <servlet-mapping>
        <servlet-name>xyz</servlet-name>
        <url-pattern>/test</url-pattern>
    </servlet-mapping>
</web-app>


Output:

hit counter