zoukankan      html  css  js  c++  java
  • 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>");
    	}
    }
    

      

  • 相关阅读:
    C# 操作ini配置文件
    2015-2016跨年感想
    HTTP 状态码总结 (HTTP Status Codes)
    简单、精准、高效的使用搜索引擎,快速的找到你想要的结果
    ASP.NET前后台交互之JSON数据
    软件开发项目做需求分析的一点心得
    我是如何自学编程的“3遍读书法”
    C#中Request.ServerVariables详细说明及代理
    C#
    JavaScript如何计算两个日期间的时间差
  • 原文地址:https://www.cnblogs.com/Scorpicat/p/12357596.html
Copyright © 2011-2022 走看看