To implement the Save Access data, you cannot use the session because sessions belong to the same conversation, and when you close the browser, the data is gone. Therefore, you can use the Application object because the application is in the same browser, and you can save the data as long as it is accessed using the same browser. However, to permanently save the access data, you can save the data in a file, such as a TXT file.
Therefore, using the Session object +application object +txt file
The following is the implementation process:
Create a Count.java class:
Package com.sunlawer.servlet;
Import Java.io.BufferedReader;
Import Java.io.File;
Import java.io.FileNotFoundException;
Import Java.io.FileReader;
Import Java.io.FileWriter;
Import Java.io.PrintWriter;
Import Javax.servlet.http.HttpServlet; /** * Statistics Access * @author SUN * */public class Counter extends httpservlet{private static final long Serialversionuid
= 1L; /** * Write File method * @param filename * @param count */public static void WriteFile (String filename,long count) {try
{PrintWriter out=new printwriter (new FileWriter (filename));
Out.println (count);
Out.close ();
}catch (Exception e) {e.printstacktrace (); /** * Read File method * @param filename * @return/public static long ReadFromFile (String filename) {file file
=new File (filename);
Long count=0;
if (!file.exists ()) {try{file.createnewfile ();
}catch (Exception e) {e.printstacktrace ();
} WriteFile (filename,0); } try{bufferedreader in=new bufferedreader (NEW filereader (file));
try{Count=long.parselong (In.readline ());
}catch (Exception e) {e.printstacktrace ();
}}catch (FileNotFoundException e) {e.printstacktrace ();
return count;
}
}
Display the implementation of the traffic on the JSP page
For example, in the anli.jsp file:
<%
Counter countfilehandler=new Counter ();
Long count=0;
if (Application.getattribute ("Count") ==null) {
count=countfilehandler.readfromfile (Request.getrealpath ("/") + "Count.txt");
Application.setattribute ("Count", new Long (count));
}
Count= (Long) application.getattribute ("Count");
if (Session.isnew ()) {
count++;
Application.setattribute ("Count", count);
Update file directory
countfilehandler.writefile (Request.getrealpath ("/") + "Count.txt", count);
%>
clicks: <%=count%>