JSP实现网页访问统计(2)

import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServlet; public class Counter extends HttpServlet{ //写入文件的方法 public static void write2File(String filename, long count){ try{ PrintWriter out = new PrintWriter(new FileWriter(filename)); out.println(count); out.close(); } catch (IOException e) { // TODO: handle exception e.printStackTrace(); } } //读文件的方法 public static long readFromFile(String filename){ File file = new File(filename); long count = 0; if(!file.exists()){ try { file.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } write2File(filename, 0); } try{ BufferedReader in = new BufferedReader(new FileReader(file)); try{ count = Long.parseLong(in.readLine()); } catch (NumberFormatException e) { // TODO: handle exception e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { // TODO: handle exception e.printStackTrace(); } return count; } }

jsp文件代码:

<%@page import="org.servlet.count.Counter"%> <%@ page language="java" import="java.util.*" pageEncoding="GB2312"%> <html> <head> <title>java 计数器程序</title> </head> <body> <% Counter CountFileHandler = new Counter(); long count = 0; if(application.getAttribute("count") == null){ count = CountFileHandler.readFromFile(request.getRealPath("https://www.jb51.net/") + "count.txt"); application.setAttribute("count", new Long(count)); } count = (Long)application.getAttribute("count"); if(session.isNew()){ count++; application.setAttribute("count", count); //更新文件目录 CountFileHandler.write2File(request.getRealPath("https://www.jb51.net/") + "count.txt",count); } %> 访问人数:<%=count %> </body> </html>

以上四种方法,是每一次改进才得到的方法,如果要实现网站访问统计,当然最后一种是最好的,知识不是一步登天,需要在问题上不断改进,获得最终的解决方案,当然最后一种不一定是最好的,实现策略上,如果可以利用数据库也是可以的,但我认为每次访问网站都要读和写数据库,这样效率就降低了。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wzfypz.html