编写一个过滤器:
package org.jeemp. config ;
import java.io.IOException;
import java.util.Iterator;
import java.util. Map ;
import java.util.Set;
import javax. servlet . Filter ;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.Servlet request ;
import javax.servlet.ServletResponse;
import javax.servlet. annotation .WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jeemp.utils.IpUtils;
@WebFilter(urlPatterns="/*")
public class IpFilter implements Filter {
private static final Long LIMITED_TIME_MILLIS = 60 * 60 * 1000;
private static final int LIMIT_NUMBER =;
private static final int MIN_SAFE_TIME =;
private FilterConfig config;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.config = filterConfig;
}
@SuppressWarnings("unchecked")
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
ServletContext context = config.getServletContext();
Map<String, Long> limitedIpMap = (Map<String, Long>) context.getAttribute("limitedIpMap");
filterLimitedIpMap(limitedIpMap);
String ip = IpUtils.getRemoteHost(request);
System.err.println("ip:"+ip);
if (isLimitedIP(limitedIpMap, ip)) {
long limitedTime = limitedIpMap.get(ip) - System.currentTimeMillis();
request.setAttribute("remainingTime", ((limitedTime /) + (limitedTime % 1000 > 0 ? 1 : 0)));
System.err.println("ip访问过于频繁:"+ip);
return;
}
Map<String, Long[]> ipMap = (Map<String, Long[]>) context.getAttribute("ipMap");
if (ipMap.containsKey(ip)) {
Long[] ipInfo = ipMap.get(ip);
ipInfo[] = ipInfo[0] + 1;
System.out.println("当前第[" + (ipInfo[]) + "]次访问");
if (ipInfo[] > LIMIT_NUMBER) {
Long ipAccessTime = ipInfo[];
Long currentTimeMillis = System.currentTimeMillis();
if (currentTimeMillis - ipAccessTime <= MIN_SAFE_TIME) {
limitedIpMap.put(ip, currentTimeMillis + LIMITED_TIME_MILLIS);
request.setAttribute("remainingTime", LIMITED_TIME_MILLIS);
System.err.println("ip访问过于频繁:"+ip);
request.getRequestDispatcher("/error/overLimitIP").forward(request, response);
return;
} else {
initIpVisitsNumber(ipMap, ip);
}
}
} else {
initIpVisitsNumber(ipMap, ip);
System.out.println("您首次访问该网站");
}
context.setAttribute("ipMap", ipMap);
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
private void filterLimitedIpMap(Map<String, Long> limitedIpMap) {
if (limitedIpMap == null) {
return;
}
Set<String> keys = limitedIpMap.keySet();
Iterator<String> keyIt = keys.iterator();
long currentTimeMillis = System.currentTimeMillis();
while (keyIt.hasNext()) {
long expireTimeMillis = limitedIpMap.get(keyIt.next());
if (expireTimeMillis <= currentTimeMillis) {
keyIt.remove();
}
}
}
private boolean isLimitedIP(Map<String, Long> limitedIpMap, String ip) {
if (limitedIpMap == null || ip == null) {
return false;
}
Set<String> keys = limitedIpMap.keySet();
Iterator<String> keyIt = keys.iterator();
while (keyIt.hasNext()) {
String key = keyIt.next();
if (key.equals(ip)) {
return true;
}
}
return false;
}
private void initIpVisitsNumber(Map<String, Long[]> ipMap, String ip) {
Long[] ipInfo = new Long[];
ipInfo[] = 0L;
ipInfo[] = System.currentTimeMillis();
ipMap.put(ip, ipInfo);
}
}
创建一个监听器:需要初始化两个容器
package org.jeemp.config;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.slfj.Logger;
import org.slfj.LoggerFactory;
public class MyListener implements ServletContextListener{
private Logger logger = LoggerFactory.getLogger(MyListener.class);
@Override
public void contextInitialized(ServletContextEvent sce) {
logger.info("liting: contextInitialized");
System.err.println("MyListener初始化成功");
ServletContext context = sce.getServletContext();
Map<String, Long[]> ipMap = new HashMap<String, Long[]>();
context.setAttribute("ipMap", ipMap);
Map<String, Long> limitedIpMap = new HashMap<String, Long>();
context.setAttribute("limitedIpMap", limitedIpMap);
logger.info("ipmap:"+ipMap. toString ()+";limitedIpMap:"+limitedIpMap.toString()+"初始化成功。。。。。");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
}
启动类里面添加以上监听器和过滤器的扫描包路径
@ServletComponentScan(basePackages="org.jeemp")