实现网站在线访问计数器功能,网站的初始值设置为1000
(1)创建CountFilter的类,实现javax。servlet.Filter接口,是一个过滤器对象,通过过滤器实现统计网站人数功能:package com.lixiyu;
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;
/**
* 统计过滤器
* @author lixiyu
*/
public class CountFilter implements Filter {
// 来访数量
private int count;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// 获取初始化参数
String param = filterConfig.getInitParameter("count");
// 将字符串转换为int
count = Integer.valueOf(param);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// 访问数量自增
count ++;
// 将ServletRequest转换成HttpServletRequest
HttpServletRequest req =(HttpServletRequest)request;
// 获取ServletContext
ServletContext context =req.getSession().getServletContext();
// 将来访数量值放入到ServletContext中
context.setAttribute("count", count);
// 向下传递过滤器
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
(2)配置已创建的CountFilter对象,设置初始值为1000,配置web.xml:<?xml version="1.0" encoding="UTF-8"?>
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
CountFilter
com.lixiyu.CountFilter
count
1000
CountFilter
/index.jsp
(3)创建程序首页index.jsp,在该页面通过JSP内置对象Application获取计数器的值:
pageEncoding="UTF-8"%>
人数统计欢迎光临,
您是本站的第【
】位访客!