Servlet 过滤器短时间恶意刷请求
博客专区 > 目翟 的博客 > 博客详情
Servlet 过滤器短时间恶意刷请求
目翟 发表于4年前
Servlet 过滤器短时间恶意刷请求
  • 发表于 4年前
  • 阅读 35
  • 收藏 0
  • 点赞 0
  • 评论 0

标题:腾讯云 新注册用户域名抢购1元起>>>   

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



标签: 请求 过滤器
共有 人打赏支持
粉丝 4
博文 25
码字总数 26183
×
目翟
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: