Creating a Hit Counter Using Applications


A session lets you track one user at a timean application lets you share data between many users. To access the current application, you can use the built-in JSP application object. Like the session object, the application object is based on the javax.servlet.http.HttpSession interface.

In the previous example, you saw how to create a session attribute named counter that stores the number of times the user has visited the page in the current session. In the same way, you can create an application attribute named counter that holds the total number of times anyone in the same application has viewed a JSP page:

 Integer counter = (Integer)application.getAttribute("counter"); if (counter == null) {     counter = new Integer(1); } else {     counter = new Integer(counter.intValue() + 1); } application.setAttribute("counter", counter); 

You can see this at work in ch05_08, where the code supports an application counter (not a session counter) that stores the number of visits in the current application:

 <HTML>     <HEAD>         <TITLE>A hit counter using applications</TITLE>     </HEAD>     <BODY>         <H1>A hit counter using applications</H1>         <%         Integer counter =             (Integer)application.getAttribute("counter");         if (counter == null) {             counter = new Integer(1);         } else {             counter = new Integer(counter.intValue() + 1);         }         application.setAttribute("counter", counter);         %>         Number of times you've been here: <%=counter%>     </BODY> </HTML> 

You can see what this JSP looks like in Figure 5.10. When the user refreshes this page, the number of hits automatically increments, as shown in the figure. And when other users open the same page, the count also increments, because the data in the application object is shared among those users.

Figure 5.10. Using an application-based hit counter.


That's exactly what Chat needssome way of sharing stored data between multiple users of the same JSP.



    Java After Hours(c) 10 Projects You'll Never Do at Work
    Java After Hours: 10 Projects Youll Never Do at Work
    ISBN: 0672327473
    EAN: 2147483647
    Year: 2006
    Pages: 128

    Similar book on Amazon

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net