Bitcoin

Bitcoin
Bitcoin

JSP - Visitor/Hit Counter

Page counter means the number of times the page has been visited by the users. To implement a hit counter you can make use of the Application Implicit object and associated methods getAttribute() and setAttribute().
This object is a representation of the JSP page through its entire lifecycle. This object is created when the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy() method.
Following is the syntax to set a variable at application level −
application.setAttribute(String Key, Object Value);
You can use the above method to set a hit counter variable and to reset the same variable. Following is the method to read the variable set by the previous method −
application.getAttribute(String Key);
Every time a user accesses your page, you can read the current value of the hit counter and increase it by one and again set it for future use.

visitorCount.jsp

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

web.xml

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

Output:

hit counter

No comments:

Post a Comment

Facebook