Servlet学习之计数器

源码呈现,用户校验登录Servlet及计数完整代码:

package com.zkj;
//通过继承HttpServlet开发
import javax.servlet.http.*;
import java.io.*;
import javax.servlet.*;

public class Check extends HttpServlet{

  public void init() throws ServletException{
    try{
      System.out.println("Init被调用");
      //添加网页访问次数的功能
      //获取当前次数
      FileReader fr = null;
      BufferedReader bfr = null;
      String sCount;
      try
      {
        fr = new FileReader("D:\Data.txt");
        bfr = new BufferedReader(fr);
        sCount = bfr.readLine();

        this.getServletContext().setAttribute("loginTimes", sCount);
      }catch(Exception e){
      }finally{
        if (bfr != null)
          bfr.close();
      }

    }catch(Exception e){
    }
  }

  public void destroy(){
    try{
      //再将新的次数写回文件
      FileWriter fw = null;
      BufferedWriter bfw = null;
      try{
        fw = new FileWriter("D:\Data.txt");
        bfw = new BufferedWriter(fw);
        bfw.write("" + this.getServletContext().getAttribute("loginTimes"));
      }catch(Exception e){
      }
      finally{
        if (bfw != null)
          bfw.close();
      }

      System.out.println("Destroy被调用");
    }catch(Exception e){
    }  
  }

  //处理get请求
  public void doGet(HttpServletRequest req, HttpServletResponse res){
    System.out.println("service it");
    try{

      //接收用户名和密码
      String u=req.getParameter("username");
      String p=req.getParameter("passwd");
      //连接数据库
      UserBeanManager ubm = new UserBeanManager();
      boolean bHas = ubm.checkUserValid(u, p);

      //验证
      //u.equals("zkj") && p.equals("123")
      if (bHas)
      {
        //合法用户进入

        String chk = req.getParameter("keep");
        if (chk != null){
          //将用户名和密码保存在cookie
          Cookie ck = new Cookie("myname", u);
          Cookie ps = new Cookie("mypass", p);
          //设置生命长
          ck.setMaxAge(14*24*3600);
          ps.setMaxAge(14*24*3600);
          //回写到客户端
          res.addCookie(ck);
          res.addCookie(ps);
        }

        //计数增加写到ServletContext
        String sCount = this.getServletContext().getAttribute("loginTimes").toString();
        int nCount = Integer.parseInt(sCount);
        nCount ++;
        this.getServletContext().setAttribute("loginTimes", nCount + "");

        //传送name到welcome
        res.sendRedirect("welcome?uname=" + u);
      }else{
        res.sendRedirect("login");
      }

    }catch(Exception e){
      e.printStackTrace();
    }
  }

  //处理post请求 一般是共用,用一个业务逻辑
  public void doPost(HttpServletRequest req, HttpServletResponse res){
    this.doGet(req, res);
  }

}

为了避免多次读写文件,需要把读原始计数在init中,保存计数值写到destroy

原文地址:https://www.cnblogs.com/jiqiwoniu/p/4412336.html