zoukankan      html  css  js  c++  java
  • 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>次

  • 相关阅读:
    循序渐进学Python 1 安装与入门
    常用yum命令小结
    为CentOS配置网易163的yum源
    PHP合并数组+与array_merge的区别
    让Docker功能更强大的10个开源工具
    Docker入门系列8
    Docker入门系列7 动态映射端口port mapping
    e 的由来
    ROS教程5 使用串口
    1 ROS+ 使用ORB_SLAM2进行全场定位
  • 原文地址:https://www.cnblogs.com/beast-king/p/3851402.html
Copyright © 2011-2022 走看看