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????
源代码见附件

你可能感兴趣的:(java,sql,jsp,xml,servlet)