<pre name="code" class="java">public class CountFilter implements Filter {
public CountFilter() {
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
<span style="white-space:pre"> </span>//此處單開一個線程統計訪問量,可以加快正常內容的訪問速度,但統計的實時性沒那麼好
new MyThread(request.getServletContext()).start();
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throws ServletException {
}
}
class MyThread extends Thread{
private ServletContext context;
private static Object obj = new Object();
public MyThread(ServletContext context) {
this.context = context;
}
@Override
public void run() {
synchronized (obj) {
Integer count = (Integer) context.getAttribute("count");
if (count == null) {
count = new Integer(0);
}
count++;
context.setAttribute("count", count);
}
}
public class MyservletContextListener implements ServletContextListener {
@Override<span style="color:#ff0000;">//服務器項目啓動時從文件中讀取出上次保存的訪問量</span>
public void contextInitialized(ServletContextEvent sce) {
try {
String path = sce.getServletContext().getRealPath("count.txt");
BufferedReader br = new BufferedReader(new FileReader(path));
String line = br.readLine();
Integer count = Integer.valueOf(line);
sce.getServletContext().setAttribute("count", count);
br.close();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override<span style="color:#ff0000;">//服務器關閉時將訪問量保存到文件</span>
public void contextDestroyed(ServletContextEvent sce) {
try {
String path = sce.getServletContext().getRealPath("count.txt");
String count = ""+sce.getServletContext().getAttribute("count");
PrintWriter pw = new PrintWriter(path);
pw.println(count);
pw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}