[jsp website counting function] application session

4889 단어 application
There are many ways to implement website counters in jsp pages, and the most common one is to use application and session objects. The application object can be shared by all users; the session is shared by a single user, and the user can use the session from the beginning of accessing the system to the time he exits the system. The implementation idea of ​​the website counter is: when the system creates a session object, add 1 to the count variable saved in the application
 
count.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">



<html>

  <head>

  </head>

  

  <body>

    <%!

        synchronized void countPeople(){

            ServletContext application = this.getServletContext();

            Integer number = (Integer) application.getAttribute("count");

            if(number == null){

                number = new Integer(1);

                application.setAttribute("count", number);

            }

            else{

                number = new Integer(number.intValue() + 1);

                application.setAttribute("count",number);

            }

        }

     %>

     

     <% 

         if(session.isNew()){

             countPeople();

         }

         Integer yourNumber = (Integer) application.getAttribute("count");

     %>

     <p></p><%= yourNumber %></body>

</html>

 
In the above code, in order to avoid concurrency problems with the application object, the synchronized keyword is used. In order to avoid the page refresh problem, the session.isNew() judgment is added. If the session object is newly created, it indicates that the user starts to access the system and the counter is incremented by 1; when the user refreshes the current page, since the session object is not newly created, it is avoided. Repeat the problem of adding 1
 
In fact, when implementing the counter function, you need to pay attention to some details, such as frequent refresh and concurrent access. Since the life cycle of the application object is related to server start and stop, if the server restarts due to a problem, the counters saved by the application will be cleared. To solve this problem, you can save the value of the counter in a file, and then add 1 to the counter by using the function of reading and writing files.

좋은 웹페이지 즐겨찾기