JSP---网页计数器(数据存在服务器的文本文件,防web应用程序关闭后数据丢失,防刷数据)

1、建立进行读写文件的java类

//写文件
public static void WriteFile(String filename,long counter) throws IOException {

 PrintWriter out=new PrintWriter(new FileWriter(filename));
 out.println(counter);
 out.close();
}


//读文件
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页面调用

<%
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);
}
%>
该页面已被访问<font color='red'><%=counter%></font>次

原文地址:https://www.cnblogs.com/beast-king/p/3851402.html