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.
[java]application.setAttribute(String Key, Object Value);[/java]
Following is the syntax to get the variable.
[java]application.getAttribute(String Key);[/java]
Example
Following is an example for JSP Hits Counter, here used setAttribute and getAttribute methods.
Index.jsp
[html]<%@ page import="java.io.*,java.util.*" %>
<html>
<head>
<title>Applcation object in JSP</title>
</head>
<body bgcolor="skyblue">
<center>
<img src="E:/splessons.png"></br>
<a href="http://www.splessons.com">Splessons.com</a></br>
<%
Integer hitsCount =
(Integer)application.getAttribute("hitCounter");
if( hitsCount ==null || hitsCount == 0 ){
/* First visit */
out.println("Welcome to SPlessons");
hitsCount = 1;
}else{
/* return visit */
out.println("Welcome back to SPlessons!");
hitsCount += 1;
}
application.setAttribute("hitCounter", hitsCount);
%>
<p>Total number of visits: <%= hitsCount%></p>
</center>
</body>
</html>[/html]
Output
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.
Characterize a database table with a solitary count, let us say hitcount. Give a zero value to it.
With each hit, read the table to get the estimation of hitcount.
Increment the estimation of hitcount by one and redesign the table with new esteem.
Show new estimation of hitcount as aggregate page hit checks.
One can apply the above logic for all the pages.
Summary
Key Points
setAttribute is the method to set the variable in application.
JSP Hits Counter - getAttribute is the method to get the variable.