Latest web development tutorials

JSP traffic stats

Sometimes we need to know the number of times a page is accessed, then we need to add the page count in the page, the page access statistics generally when the user first loads accumulated on the number of visits to the page.

To implement a counter, you can use the application implicit object and related methods getAttribute () and setAttribute () to achieve.

This object represents the entire life cycle of JSP pages. This object is created when the JSP page is initialized, the object is deleted when the JSP page calls jspDestroy ().

The following variables are created in the application syntax:

application.setAttribute(String Key, Object Value);

You can use the above method to set a counter variable and update the value of the variable. Read the variable as follows:

application.getAttribute(String Key);

When each page is accessed, you can read the current value of the counter and is incremented by 1, then re-set, the next time a user accesses the new value will be displayed on the page.


Examples Demo

This example describes how to use JSP to calculate the total number of people visited a particular page. If you want to calculate the total traffic to your site using pages, then you have all the code on the JSP page.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.io.*,java.util.*" %>
<html>
<html>
<head>
<title>访问量统计</title>
</head>
<body>
<%
    Integer hitsCount = 
      (Integer)application.getAttribute("hitCounter");
    if( hitsCount ==null || hitsCount == 0 ){
       /* 第一次访问 */
       out.println("欢迎访问本教程!");
       hitsCount = 1;
    }else{
       /* 返回访问值 */
       out.println("欢迎再次访问本教程!");
       hitsCount += 1;
    }
    application.setAttribute("hitCounter", hitsCount);
%>

<p>页面访问量为: <%= hitsCount%></p>


</body>
</html>

Now we will above code placed on main.jsp files, and access http: // localhost: 8080 / testjsp / main.jsp file. You will see the page will generate a counter each time we refresh the page, the counter will change (increase by 1 each refresh).

You can also access a different browser, the counter will increase after each visit 1. As follows:


Reset Counter

Using the above method, after the web server is restarted, the counter is reset to 0, that is, to retain the previous data will disappear and you can use at several ways to solve the problem:

  • Define a statistics page views count data table in the database, the field is hitcount, hitcount default value is 0, the statistical data is written to the data table.
  • When you visit our table to be read hitcount field.

  • Let hitcount every time access is incremented by one.
  • Displayed on the page as the new value hitcount visited pages.

  • If you need the number of visits to each page, you can use the above logic to add code to all pages.