Servlet 过滤器短时间恶意刷请求

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;
    }
}



你可能感兴趣的:(过滤器,请求)