• Post Reply Bookmark Topic Watch Topic
  • New Topic

Page HitCounter in JSP?

 
Mike London
Ranch Hand
Posts: 1290
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to implement a page hit counter from my JSP page. The code below calls a small Java class that does the actual increment and stores the new value in a text file.
All works OK, except that now I'm trying to only have the counter update ** once per session **.
That is, I don't want the user to refresh the page or go to another page and then come back to the home page and have the hit counter increment again.
I can't get this session stuff to work: the counter increments everytime no matter what.
Below, I have some code that (tries) to set a session variable.
In the code:
out.println("setVisitorCount second time.... = " + setVisitorCount);
The session variable reports "true", meaning it was set.
However, if I refresh the page or go to another page in the site and come back, the first attempt to retrieve the session variable is always null.
What am I missing?
I appreciate, in advance, any advice or replies.
-- Mike

<%

String setVisitorCount = (String) session.getAttribute("vcnt");
out.println("setVisitorCount = " + setVisitorCount);
if ( (setVisitorCount == null) || (setVisitorCount.trim().length() == 0) )
{
// create a session variable so we don't increment this variable everytime we visit the home page
// in the same session

session.setAttribute("vcnt", "true");

setVisitorCount = (String) session.getAttribute("vcnt");
out.println("setVisitorCount second time.... = " + setVisitorCount);
String svrRoot = request.getRealPath("/");
UpdateHitCounter ht = new UpdateHitCounter();
int visitorCount = ht.incrementHitCounter(true, svrRoot);
out.println("You are visitor number: " + visitorCount);
ht = null;
}
%>
 
steve souza
Ranch Hand
Posts: 862
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't see where you get the session. Based on what is happening I think every time you go to that page the logic gives the user a new session.
Here is a link that does something similar to what you are trying to do with an HttpSessionBindingListener
http://www.jamonapi.com/httpsession_sample.html
steve - http://www.jamonapi.com - a performance tuning api
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!