天天看点

网站访问计数器

//filter过滤器
package filter;

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;
/**
 * 网站访问计数器,初始值为5000
 * @author Administrator
 *
 */
public class MyFilter implements Filter {

	//定义私有全局变量
	private int count;
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		String param = filterConfig.getInitParameter("count");
		//将值拿到,可以进行下一步的操作
		count = Integer.valueOf(param);
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		//没访问一次页面,数量+1
		count++;
		//由于客户端发送的请求都是HTTP,所以将request转换成HttpServletRequest
		HttpServletRequest req = (HttpServletRequest)request;
		//通过会话得到计数
		ServletContext context = req.getSession().getServletContext();
		//修改计数值,count
		context.setAttribute("count", count);
		//过滤处理
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {

	}

}

//web.xml配置
<!-- 过滤器声明 -->
	<filter>
		<!-- 过滤器名称 -->
		<filter-name>myFilter</filter-name>
		<!-- 过滤器完整类名 -->
		<filter-class>filter.MyFilter</filter-class>
		<init-param>
			<param-name>count</param-name>
			<param-value>5000</param-value>
		</init-param>
	</filter>
	<!-- 过滤器映射 -->
	<filter-mapping>
		<!-- 过滤器名称 -->
		<filter-name>myFilter</filter-name>
		<!-- 过滤器URL映射 -->
		<url-pattern>/filter.jsp</url-pattern>
	</filter-mapping>

//jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 通过application获取服务器中的count -->
	您是本站的第<%=application.getAttribute("count") %>位访问
</body>
</html>
           

在服务器启动的情况下,访问的数量为5000+(默认为5000),但是如果重启服务器将重新从5000开始计数;