网页计数器想必大家都有见到过吧,记录每一个访问者,下面有个不错的示例,感兴趣的朋友可以参考下
代码如下://过滤器类 public class EcondingFilter implements Filter { private String charset = null; private ServletContext context = null; private String path = ""; /** * 在销毁前将数据存入本地文件中 */ public void destroy() { //获取servleContext中的属性的那个值 String nums = (String) context.getAttribute("nums"); //创建写入流 FileWriter fw = null; BufferedWriter bw = null; try { fw = new FileWriter(path); bw = new BufferedWriter(fw); bw.write(nums); } catch (Exception e) { e.printStackTrace(); } finally { try { if (bw != null) { bw.close(); } if (fw != null) { fw.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("filter销毁"); } 代码如下:public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub System.out.println("doFilter前"); String path = ((HttpServletRequest)request).getServletPath();//获取每次访问的action的相对路径 <img alt="" src="http://img.blog.csdn.net/20130728233435953?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQva2tyZ3diag==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center"><img alt="" src="http://img.blog.csdn.net/20130728233445625?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQva2tyZ3diag==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center"> //判断路径,如果是登陆的那个action,就让保存的context里面的那个属性加1 if(path.endsWith("/login.action")){ context.setAttribute("nums",Integer.parseInt(context.getAttribute("nums").toString())+1+""); } request.setCharacterEncoding(charset); response.setCharacterEncoding(charset); chain.doFilter(request, response); System.out.println("doFilter后"); } 代码如下:public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub System.out.println("filter初始化"); //获取编码格式 charset = filterConfig.getInitParameter("encoding"); //获取servletContext context = filterConfig.getServletContext(); System.out.println(charset); path = context.getRealPath(""); File file = new File("D:text.txt"); if (!file.exists()) {//判断文件是否存在 // 如果文件不存在,就创建一个文件,保存在D盘中 file = new File("d:text.txt"); FileWriter fw = null; BufferedWriter bw = null; try { fw = new FileWriter(file); bw = new BufferedWriter(fw); bw.write(0 + "");// 写入初始化数据0 } catch (Exception e) { e.printStackTrace(); } finally { try { if (bw != null) { bw.close(); } if (fw != null) { fw.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } //当每次tomcat启动服务时,进行读取创建的那个文件 path = "d:text.txt"新闻热点
疑难解答