index.jsp
<%@ page language="java" contentType="text/html; charset=gb2312"
pageEncoding="gb2312" isErrorPage="true"%>
<%request.setCharacterEncoding("gb2312"); %>
<%@page import="com.baozi.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>访问计数</title>
</head>
<body>
<h2>您是本站的第[<%=application.getAttribute("count") %>]位访客!</h2>
</body>
</html>
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
}
}