jsp代码
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>统计页面访问IP数</title>
</head>
<body>
<table>
<tr>
<td>ip address</td>
<td>count</td>
</tr>
<c:forEach items="${applicationScope.ipCountMap }" var="entry">
<tr>
<td>${entry.key }</td>
<td>${entry.value } </td>
</tr>
</c:forEach>
</table>
</body>
</html>
Filter
package cn.ccnu.filter;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
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 IPFilter implements Filter{
private ServletContext servletContext;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
servletContext = filterConfig.getServletContext();
Map<String, Integer> ipMap = Collections.synchronizedMap(new LinkedHashMap<String, Integer>());
servletContext.setAttribute("ipCountMap", ipMap);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
String ipAddress = req.getRemoteAddr();
Map<String, Integer> ipCountMap = (Map<String, Integer>) servletContext.getAttribute("ipCountMap");
Integer count = ipCountMap.get(ipAddress);
if(count == null){
ipCountMap.put(ipAddress, 1);
}else{
count += 1;
ipCountMap.put(ipAddress, count);
}
servletContext.setAttribute("ipCountMap", ipCountMap);
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
部署描述文件
<!-- Filter部署 -->
<filter>
<filter-name>IPFilter</filter-name>
<filter-class>cn.ccnu.filter.IPFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>IPFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>