• 15 Servlet——利用ServletContext制作网站访问计数器


    背景

    我们以 第13节 的案例为背景,添加网站访问的计数功能。

    设计思路

    创建一个文件:用来存储网站访问的次数

    从文件获取:在初始化InitServlet中的init()方法中,从文件获取已经存好的值作为已经访问的数量

    在用户登录的LoginServlet和3天免登陆的CookieServlet中添加往ServletContext对象中添加获取和自增计数变量的代码。(-_-||好长的一句话)

    • 获取:通过getAttribute()获取目标数据变量
    • 自增:获取之后变量自增,又通过setAttribute()覆盖原有值

    写入值到文件:当服务器关闭,ServletContext对象会被销毁,所以我们需要在InitServlet的destroy方法中向文件中写入ServletContext中的用来计数的变量的值。(-_-||)

    演示

    演示说明:启动服务器->登录->主页看到1->注销,再次登录->主页看到2->关闭服务器->重启服务器->登录->主页看到3

     

    代码

    InitServlet

    public class InitServlet extends HttpServlet {
    	@Override
    	public void init() throws ServletException {
    		//ServletContext对象
    		ServletContext sc = this.getServletContext();
    		//从文件中获取值
    		InputStream is = sc.getResourceAsStream("/doc/count.txt");//保存访问次数的文件路径
    		BufferedReader br = null;
    		try{
    			br = new BufferedReader(new InputStreamReader(is));
    			String countor= br.readLine();
    			System.out.println("读取countor:"+countor);
    			sc.setAttribute("countor", countor);
    		}catch(IOException e) {
    			e.printStackTrace();
    		}finally {
    			try {
    				if(br!=null) {
    					br.close();
    				}
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    		//赋值到ServletContext对象中去
    		
    	}
    	@Override
    	public void destroy() {
    		System.out.println("我被执行了1");
    		//从ServeltContext中获取值
    			//ServletContext对象
    		ServletContext sc = this.getServletContext();
    			//获取值
    		String countor = (String)sc.getAttribute("countor");
    		System.out.println("写入countor:"+countor);
    		//写入文件
    		String path = sc.getRealPath("/doc/count.txt");//保存访问次数的文件路径
    FileWriter fw = null; BufferedWriter bw = null; System.out.println("我被执行了2"); try{ System.out.println("我被执行了3"); bw = new BufferedWriter(fw = new FileWriter(path)); bw.write(countor); bw.flush(); System.out.println("我被执行了4"); }catch(IOException e) { e.printStackTrace(); }finally { try { if(bw!=null) { bw.close(); } } catch (IOException e) { e.printStackTrace(); } try { if(fw!=null) { fw.close(); } } catch (IOException e) { e.printStackTrace(); } } } }

      

    LoginServlet

    public class LoginServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
        private static String username;
        private static String password;
        private static boolean flag =false;//账号密码是否正确
    	@Override
    		protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    			//设置请求编码
    			req.setCharacterEncoding("utf-8");
    			//设置响应编码
    			resp.setContentType("text/html;charset=utf-8");
    			//获取请求数据
    				username = req.getParameter("uname");
    				password = req.getParameter("pwd");
    			//处理请求
    				LoginService ls = new LoginServiceImpl();
    				User user = ls.checkLoginService(username, password);
    			//响应
    			if(null != user) {
    				//创建cookie,实现3天免登陆
    					//我们不直接存账号密码,而是存用户的uid
    					Cookie c = new Cookie("uid",user.getUid()+"");
    					//设置有效期为3天
    					c.setMaxAge(3*24*3600);
    					//设置指定url
    					c.setPath("/200222-CookieLogin/ck");
    					//添加
    					resp.addCookie(c);
    					//创建session
    					HttpSession hs = req.getSession();
    					//设置时效
    					//将用户对象保存到session中
    					hs.setAttribute("user", user);
    					//ServletContext对象获取网站访问计数器
    					ServletContext cs = this.getServletContext();
    					int countor = Integer.valueOf((String)cs.getAttribute("countor"));
    					countor++;
    					cs.setAttribute("countor", countor+"");
    					
    				resp.sendRedirect("main");
    				return;
    			}else {
    				//请求转发
    				req.setAttribute("msg", "账号或密码错误");
    				req.getRequestDispatcher("page").forward(req, resp);
    				return;
    			}
    		}
    }
    

      

    CookieServlet

    public class CookieServlet extends HttpServlet {
    	@Override
    	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		//设置请求编码
    		req.setCharacterEncoding("utf-8");
    		//设置响应类型及编码
    		resp.setContentType("text/html;charset=utf-8");
    		//获取请求
    			//判断是否有cookie
    			Cookie[] cks = req.getCookies();
    			//处理请求
    			if(null!=cks) {
    				//从cookie中获取uid
    				String uid = "";
    				for(Cookie c : cks) {
    					if("uid".equals(c.getName())) {
    						uid = c.getValue();
    					}
    				}
    				//校验用户是否存在(使用uid)
    				CookieService ls = new CookieServiceImpl();
    				User u = ls.checkUidService(uid);
    				if(null!=u) {
    					//设置session
    					HttpSession hs = req.getSession();
    					//将用户数据保存到session
    					hs.setAttribute("user", u);
    					//ServletContext对象获取网站访问计数器
    					ServletContext cs = this.getServletContext();
    					int countor = Integer.valueOf((String)cs.getAttribute("countor"));
    					countor++;
    					cs.setAttribute("countor", countor+"");
    					//跳转主页
    					resp.sendRedirect("main");
    					return;
    				}else {
    					req.getRequestDispatcher("/page").forward(req, resp);
    					return;
    				}
    			}else {
    				req.getRequestDispatcher("/page").forward(req, resp);
    				return;
    			}
    	}
    }
    

      

    MainSerlvet

    public class MainServlet extends HttpServlet{
    	@Override
    	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		//设置请求编码格式
    		req.setCharacterEncoding("utf-8");
    		//设置响应类型及编码
    		resp.setContentType("text/html;charset=utf-8");
    		//获取session对象
    		HttpSession hs = req.getSession();
    		//获取用户对象
    		User user = (User)hs.getAttribute("user");
    		//获取用户名
    		String username = null;
    		if(user!=null) {
    			username = user.getUsername();
    		}
    		//ServletContext对象获取网站访问计数器
    		ServletContext cs = this.getServletContext();
    		String countor = (String)cs.getAttribute("countor");
    		resp.getWriter().write("<html>");
    		resp.getWriter().write("<head>");
    		resp.getWriter().write("</head>");
    		resp.getWriter().write("<body>");
    		resp.getWriter().write("欢迎登录"+username+"管理系统<hr>");
    		resp.getWriter().write("<form action='logout' method='get'>");
    		resp.getWriter().write("<input type='submit' value='注销'> ");
    		resp.getWriter().write("</form>");
    		resp.getWriter().write("<form action='page' method='get'>");
    		resp.getWriter().write("<input type='submit' value='登录'><hr>");
    		resp.getWriter().write("</form>");
    		resp.getWriter().write("网站访问次数:"+countor);
    		resp.getWriter().write("</body>");
    		resp.getWriter().write("</html>");
    	}
    }
    

      

  • 相关阅读:
    【超详细教程】使用Windows Live Writer 2012和Office Word 2013 发布文章到博客园全面总结
    Jquery+asp.net后台数据传到前台js进行解析的方法
    OWASP Top 10 – 2013, 最新十大安全隐患(ASP.NET解决方法)
    Owasp Top 10 Security Risks for 2014
    js中cookie的使用详细分析
    Cookie/Session机制详解
    ASP.NET Web API 简介
    未找到具有固定名称“System.Data.SQLite”的 ADO.NET 提供程序的实体框架提供程序
    网页被Chrome识别成英语,区域,语言,网站
    16进制字符串转换为byte数组
  • 原文地址:https://www.cnblogs.com/Scorpicat/p/12357596.html
Copyright © 2020-2023  润新知