import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@WebFilter(
urlPatterns = {"/countNum.jsp"},
initParams = {
@WebInitParam(name = "count", value = "100")
}
)
public class MyFilter implements Filter {
private int count;//访问人数
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
count++;//访问数量增加
//将ServletRequest转换为HttpServletRequest
HttpServletRequest request = (HttpServletRequest) req;
//获取ServletContext
ServletContext context = request.getServletContext();
context.setAttribute("count", count);//将数量放入
chain.doFilter(req, resp);//放开拦截
}
//初始化
public void init(FilterConfig config) throws ServletException {
String param = config.getInitParameter("count");//获取初始化参数
count = Integer.valueOf(param);
}
} |