日期:2014-05-17 浏览次数:20695 次
public class Count implements ServletContextListener{ public void contextDestroyed(ServletContextEvent arg0) { ServletContext sc = arg0.getServletContext(); Integer count = (Integer) sc.getAttribute("AccessCount"); try { PrintWriter out = new PrintWriter(new FileWriter("d:/count.txt"));// 将人数保存到文本文件 System.out.println("count:"+count); out.print(count++); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } public void contextInitialized(ServletContextEvent arg0) { Integer count = 0; ServletContext sc = arg0.getServletContext(); try { Scanner in = new Scanner(new FileReader("d:/count.txt"));// 读取已经产生的人数信息,然后进行累加 count = in.nextInt(); System.out.println(count+"--------------"); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } sc.setAttribute("AccessCount", count); } } public class Countp implements Filter{ private String id; public void destroy() { // TODO Auto-generated method stub } public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterchain) throws IOException, ServletException { HttpServletRequest re=(HttpServletRequest)request; HttpServletResponse pon=(HttpServletResponse)response; HttpSession session=re.getSession(); if(session.getId()!=null){ //判断是否同一IP跟时间 Integer count = (Integer) session.getServletContext().getAttribute("AccessCount"); if(count!=null){ System.out.println(count+"========="); session.getServletContext().setAttribute("AccessCount", count++); id = session.getId(); } } System.out.println("-------"); filterchain.doFilter(re, pon); } public void init(FilterConfig arg0) throws ServletException { }
<%=request.getSession().getServletContext().getAttribute("AccessCount")%>