过滤器实现网站计数

image.png

index.jsp

<%@ page language="java" contentType="text/html; charset=gb2312"
    pageEncoding="gb2312" isErrorPage="true"%>
<%request.setCharacterEncoding("gb2312"); %>
<%@page import="com.baozi.*" %>




访问计数


    

您是本站的第[<%=application.getAttribute("count") %>]位访客!

CountFilter

package com.baozi;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class CountFilter implements Filter {
    private int count;
    public void init(FilterConfig fConfig) throws ServletException {
        String param=fConfig.getInitParameter("count");
        count=Integer.valueOf(param);
    }
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        count++;
        //ServletRequest->HttpServletRequest,然后获取ServletContext
        ServletContext context=((HttpServletRequest)request).getSession().getServletContext();
        //将count放入ServletContext
        context.setAttribute("count", count);
        chain.doFilter(request, response);
    }
    public void destroy() {
        // TODO Auto-generated method stub
    }

}

你可能感兴趣的:(过滤器实现网站计数)