首页 > Web开发 > 详细

使用过滤器实现网站访问计数器的功能

时间:2014-01-31 12:51:38      阅读:504      评论:0      收藏:0      [点我收藏+]

创建过滤器类:

public class CountFilter implements Filter {

    private int count;//访问数量

    //初始化

@Override

    public void init (FilterConfig config) throws ServletException{

                  //获取初始化数量

                  String  param = filterConfig.getInitParameter(“count”);

                  count = Integer.valueOf(param);  

     }

@Override

     public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException ,ServletException{

                    //访问数据自增

                    count++;

                    //将ServletRequest转换为HttpServletRequest

                    HttpServletRequest req = (HttpServletRequest)request;

                    //获取ServletContext   (Application)

                     ServletContext context=req.getSession().getServletContext();

                    //将来访数量值放入到ServletContext中

                    context.setAttribute(“count”,count);

                    //向下传递过滤器

                    chain.doFilter(request, response);

      }

@Override

     public void destory(){

            

     }

}

在web.xml中配置过滤器

<filter>

     <filter-name>countfilter</filter>

      <filter-class>com.filter.CountFilter</filter-class>

<!--设置初始化参数      -->

       <init-param>

             <param-name>count</param-name>

             <param-value>5000</param-value>

       </init-param>

<filter>

<filter-mapping>

    <filter-name>countfilter</filter>

    <url-pattern>/index.jsp</url-pattern>

<filter-mapping>

使用过滤器实现网站访问计数器的功能

原文:http://www.cnblogs.com/next-open/p/3536551.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!