`

java自学===Filter类的应用,网站数量统计

阅读更多
package filterStatistic;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
//使用过滤器统计网页的访问量
public class FilterFlux extends HttpServlet implements Filter {

    private static int flux = 0;

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public synchronized void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain filterChain) throws
            ServletException, IOException {
       this.flux++;
       request.setAttribute("flux",String.valueOf(flux)); //将参数保存至request对象中
       filterChain.doFilter(request, response);
    }

    public void destroy() {
    }
}


web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <filter>
  	<filter-name>filterflux</filter-name>
  	<filter-class>filterStatistic.FilterFlux</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>filterflux</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>


index.jsp

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>使用过滤器进行网站流量统计纪录</title>
</head>

<body>
<div align="center">

  <table width="429" height="388" border="0" cellpadding="0" cellspacing="0" background="images/background.jpg">
    <tr align="center">
      <td ><%=request.getAttribute("flux")%>次</td>
    </tr>
  </table>
  <br>

</div>
</body>
</html>

输入http://localhost:8080/filter/
执行每刷新一次,增加2????
源代码见附件
分享到:
评论
2 楼 innocence0627 2012-05-05  
做得确实很不太好,每次刷新自加 事实上刷新时sessionid是不变的。。所以是不能计数的。。
1 楼 innocence0627 2012-05-05  
有些问题不可避免的要问下,若是同一个sessionid再次访问刚才的页面,会不会技术呢?刷新页面是不是也会计数呢?在filter中实现是做好不过啦,这样就不是使用独立的jsp来计数。  

相关推荐

Global site tag (gtag.js) - Google Analytics