网站页面防止恶意刷新

public class RefreshFilter implements ActionFilter {

@Override
public View match(ActionContext actionContext) {
HttpServletRequest request = actionContext.getRequest();
String requestURI = request.getRequestURI();
Cache cache = Cache.getInstance();
cache.increment(requestURI);
if (cache.isUpCount(requestURI)) {
throw new ServiceException("网络忙,请稍候再试!");
}
return null;
}

// 缓存
private static class Cache {
private static final ConcurrentHashMap<String, CopyOnWriteArrayList<Long>> map = new ConcurrentHashMap<String, CopyOnWriteArrayList<Long>>();
private static final long EXPIRE_TIME = 1000 * 10L;
private static final long CLEAR_TIME = 1000 * 2L;
private static final int MAX_REFRESH_COUNT = 5;
private static final Cache cache = new Cache();

private Cache() {
new Thread(new ClearCacheRunnable()).start();
}

public static Cache getInstance() {
return cache;
}

// 增长指定URL的点击次数
public void increment(String key) {
CopyOnWriteArrayList<Long> list = map.get(key);
if (list == null) {
map.put(key, new CopyOnWriteArrayList<Long>());
}
map.get(key).add(new Long(System.currentTimeMillis()));
}

// 是否到达指定数量
public boolean isUpCount(String key) {
CopyOnWriteArrayList<Long> list = map.get(key);
if (list == null) {
return false;
}
return list.size() > MAX_REFRESH_COUNT;
}

// 清理过期数据线程
private static class ClearCacheRunnable implements Runnable {
@Override
public void run() {
while (true) {
try {
Thread.sleep(Cache.CLEAR_TIME);
clear();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

private void clear() {
for (String key : map.keySet()) {
CopyOnWriteArrayList<Long> list = map.get(key);
for (Long date : list) {
if (System.currentTimeMillis() - date > Cache.EXPIRE_TIME) {
System.out.println(list.remove(date));
}
}
}
}
}
}

}

转载于:https://my.oschina.net/u/211184/blog/72920

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值