实现效果:
编写一个记录有多少个请求访问的监听器,通过面向全部访问路径的过滤器更新监听器中的visitCount次数。
监听器:
@WebListener
public class VisitCounterListener implements ServletContextListener {private static final String VISIT_COUNT_ATTRIBUTE = "visitCount";@Overridepublic void contextInitialized(ServletContextEvent sce) {// Web应用启动时初始化访问次数为0sce.getServletContext().setAttribute(VISIT_COUNT_ATTRIBUTE, 0);}@Overridepublic void contextDestroyed(ServletContextEvent sce) {}// 增加一个用于增加访问次数的方法,这将在过滤器中被调用public static void incrementVisitCount(ServletContext servletContext) {Integer visitCount = (Integer) servletContext.getAttribute(VISIT_COUNT_ATTRIBUTE);if (visitCount == null) {visitCount = 0;}servletContext.setAttribute(VISIT_COUNT_ATTRIBUTE, visitCount + 1);System.out.println("访问次数:" + visitCount);}// 提供一个获取当前访问次数的方法,供其他组件使用public static int getVisitCount(ServletContext servletContext) {Integer visitCount = (Integer) servletContext.getAttribute(VISIT_COUNT_ATTRIBUTE);return visitCount != null ? visitCount : 0;}
}
注意!一定要加上@WebListener注解!在WebConfig配置类中声明listener的bean组件好像没有用,只有通过注解才能正确注入容器。
过滤器:
@WebFilter(filterName = "VisitCounterFilter", urlPatterns = "/*")
public class VisitCounterFilter implements Filter {private static final Logger logger = Logger.getLogger(VisitCounterFilter.class.getName());@Overridepublic void init(FilterConfig filterConfig) throws ServletException {System.out.println("VisitCounterFilter初始化...");}@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException {// 强制类型转换为HttpServletRequest,因为我们知道在Web应用中通常处理的是HTTP请求HttpServletRequest httpRequest = (HttpServletRequest) request;ServletContext servletContext = httpRequest.getServletContext();// 在请求处理之前增加访问次数VisitCounterListener.incrementVisitCount(servletContext);// 打印访问次数logger.info("VisitCounterFilter.doFilter start"); // 进入过滤器时记录日志System.out.println("访问次数:" + VisitCounterListener.getVisitCount(servletContext));logger.info(VisitCounterListener.getVisitCount(servletContext) + "");// 继续过滤器链chain.doFilter(request, response);logger.info("VisitCounterFilter.doFilter end"); // 离开过滤器时记录日志}@Overridepublic void destroy() {System.out.println("VisitCounterFilter销毁");}
}
注意:同样的!需要使用@WebFilter注解并声明相关信息!/*则说明对所有请求进行过滤