JSP---Web page counter (data exists on the server's text file, prevent data loss after Web application shutdown, anti-brush data)

Source: Internet
Author: User
Tags readfile

1. Create a Java class to read and write files

Write a file
public static void WriteFile (String filename,long counter) throws IOException {

PrintWriter out=new PrintWriter (new FileWriter (filename));
OUT.PRINTLN (counter);
Out.close ();
}


Read the file
public static long ReadFile (String filename) {
Long couter=0;
File F=new file (filename);
if (!f.exists ()) {
try {
WriteFile (filename, 0);
} catch (IOException e) {
E.printstacktrace ();
}
}
try {
BufferedReader in=new BufferedReader (new FileReader (f));
try {
Couter=long.parselong (In.readline ());
} catch (NumberFormatException e) {
E.printstacktrace ();
} catch (IOException e) {
E.printstacktrace ();
couter=0;
}
} catch (FileNotFoundException e) {
E.printstacktrace ();
}
return couter;
}

2.jsp Page Call

<%
String realpath = Request.getsession (). Getservletcontext ()
. Getrealpath ("/")
+ "Counter.txt";
Long counter = Common.readfile (Realpath);
if (Session.getattribute ("visitor") ==null) {
 session.setattribute ("visitor", "yes");
 session.setmaxinactiveinterval (3600);
 counter++;
 common.writefile (Realpath, counter);
}
%>
This page has been accessed <font color= ' red ' ><%=counter%></font> times

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.