1. 程式人生 > >Servlet監聽統計網站歷史訪問人數

Servlet監聽統計網站歷史訪問人數

需求:求網站訪問歷史訪問人數

思路:必須有個監聽器:ServletContextListener     檔案儲存       application傳值      利用:contextInitialized和contextDestroyed實現功能

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%
//1.定義一個變數
//String num="0";
//2.取出原來的值(application)
Object obj=application.getAttribute("counter");

//3.加一
int intnum=Integer.parseInt(obj.toString());
intnum++;

 //4.再次存放在application中
application.setAttribute("counter",intnum);
 %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
    您是本網站的第<span span style="color:red;font-size:34px"><%=intnum %>個使用者</span><br>
    
  </body>
</html>

CounterListener.java

package cn.wfc.eshop.control;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class CounterListener implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
		
		System.out.println("--------------銷燬----------------");
        String root=arg0.getServletContext().getRealPath("/");
		System.out.println("------得到路徑---------"+root);
        try {
			FileWriter fw=new FileWriter(root+"WEB-INF\\count.txt");
			fw.write(arg0.getServletContext().getAttribute("counter").toString());
	              fw.close();
        } catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		// TODO Auto-generated method stub

	/*String xx=	arg0.getServletContext().getInitParameter("x");
	String yy=	arg0.getServletContext().getInitParameter("y");


	System.out.println("------------x和y的值------------"+xx+"---------------"+xx);
		System.out.println("--------------初始化--------------");
*/
		System.out.println("-------------讀取檔案了-----------------");
		String num=null;
        String root=arg0.getServletContext().getRealPath("/");
 
		try {
			//字元流
			FileReader fr=new FileReader(root+"WEB-INF\\count.txt");
			//緩衝流
			BufferedReader br=new BufferedReader(fr);
			
			  num=br.readLine();
			if(num==null){
				num="0";
			}
			 
			br.close();
			fr.close();
			arg0.getServletContext().setAttribute("counter", num);

			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
 
		
	}

}


web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <listener>
        <listener-class>cn.wfc.eshop.control.CounterListener</listener-class>
    </listener>    
    <context-param>
        <param-name>x</param-name>
        <param-value>1000</param-value>
    </context-param>
    <context-param>
        <param-name>y</param-name>
        <param-value>100</param-value>
    </context-param>
</web-app>

目錄結構: