package com.wiker; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; @WebFilter(urlPatterns={"/*"}) public class IpCountFilter implements Filter { private final static String sessionKey = "SESSION_IP_COUNT"; private final static int maxRequest = 10; //最大次數 private final static int time=30000; //時間段(毫秒) public void destroy() { // TODO Auto-generated method stub } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("進入過濾器"); HttpServletRequest req = (HttpServletRequest) request; IpCount t = (IpCount) req.getSession().getAttribute(sessionKey); if(t == null){ t = new IpCount(); t.setFirstTime(System.currentTimeMillis()); t.setTimes(1); req.getSession().setAttribute(sessionKey, t); System.out.println("第一次進入過濾器"+t.getTimes()); chain.doFilter(request, response); }else{ if(System.currentTimeMillis()-t.getFirstTime()<=time){ if(t.getTimes()<=maxRequest){ t.setTimes(t.getTimes()+1); req.getSession().setAttribute(sessionKey, t); System.out.println("小於規定時間內的請求次數,放行1:"+t.getTimes()); chain.doFilter(request, response); }else{ System.out.println("超過了規定時間內的請求次數"+t.getTimes()); } }else{ t.setFirstTime(System.currentTimeMillis()); t.setTimes(1); req.getSession().setAttribute(sessionKey, t); System.out.println("小於規定時間內的請求次數,放行2:"+t.getTimes()); chain.doFilter(request, response); } } } public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } } class IpCount{ private long firstTime; private int times; public long getFirstTime() { return firstTime; } public void setFirstTime(long firstTime) { this.firstTime = firstTime; } public int getTimes() { return times; } public void setTimes(int times) { this.times = times; } }