index.jsp
<h1>欢迎来到我主页,此页面已被访问<%=application.getAttribute("count")%>次!</h1>
web.xml
<filter>
<filter-name>countFilter</filter-name>
<filter-class>com.lyq.CountFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>countFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
CountFilter.java
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req=(HttpServletRequest) request;
HttpServletResponse res=(HttpServletResponse) response;
ServletContext application=req.getSession().getServletContext();
if (application.getAttribute("count")!=null) {
Long count=(Long) application.getAttribute("count");
application.setAttribute("count", ++count);
} else {
application.setAttribute("count", new Long(1));
}
chain.doFilter(req, res);
}
P84页
原文:http://www.cnblogs.com/ganjun/p/5043468.html