`

限制频繁刷新

    博客分类:
  • java
阅读更多
通过session限制用户频繁(限制了一定时间里最多能刷多少次--刷新频率)刷新某个页面:
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 调用方式:在页面中直接调用下面代码
	StopRefresh stopRefresh = new StopRefresh();
	stopRefresh.limitTime =4;//可以不设置,默认10秒
	stopRefresh.refreshCount=2;//可以不设置,默认5次
	stopRefresh.redirectPage="/index.jsp";////可以不设置,/index.jsp
	stopRefresh.blackPage="/index.jsp";////可以不设置,/index.jsp
	stopRefresh.blackList = "192.168.61.110,2009-08-03 10:00:00,20;";//后面一定要有分号
	if(stopRefresh.stopRefreshPage(request,response)){
		return;
	}

 * @author Administrator
 *
 */
public class StopRefresh {
	
	//刷新的时间段,单位:秒
	public int limitTime = 10;

	//刷新的时间段的最大刷新次数
	public int refreshCount=5;
	
	//超过刷新次数后跳转的页面
	public String redirectPage = "/include/functionremind.htm";
	
	//192.168.61.110,yyyy-MM-dd HH:mm:ss,10;192.168.61.111,yyyy-MM-dd HH:mm:ss,100(IP,具体开始时间,禁用时间)
	public String blackList = "";
	
	public String blackPage = "/include/functionremind.htm";
	
	public static final SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	/**
	 * 阻止频繁刷新同一页面
	 */
	@SuppressWarnings("unchecked")
	public boolean stopRefreshPage(HttpServletRequest request,HttpServletResponse response) throws IOException{
		
		//判断是否超出次数或黑名单
		boolean isOverTime = false;
		
		//PrintWriter out = response.getWriter();
		String htmlContent="<script type=\"text/javascript\">window.location.href='"+redirectPage+"'</script>";
		
		String curPath = request.getServletPath();//当前路径
		int latestRefreshNum = 0;//最后一次保存的刷新
		
		TreeMap<Date,Integer> stopRefreshMap = null;
		HttpSession session = request.getSession();
		
		if(null != session.getAttribute("stopRefreshMap"+curPath)){
			stopRefreshMap = (TreeMap<Date,Integer>)session.getAttribute("stopRefreshMap"+curPath);
			
			if(stopRefreshMap.size()!=0){
				Date latestDate = stopRefreshMap.lastKey();//上一次刷新的次数
				latestRefreshNum = stopRefreshMap.get(latestDate)+1;//次数加1
				
				Date newDate = new Date();
				//out.println(newDate);
				stopRefreshMap.put(newDate, latestRefreshNum);
				
				//最新刷新时间的前10秒的时间
				Date tempDate = new Date(newDate.getTime() - limitTime*1000L);
				
				//删除不需要的对象(超过limitTime秒前的对象)
				Iterator<Date> iterator = stopRefreshMap.keySet().iterator();
				while(iterator.hasNext()){
					Date date = iterator.next();			
					if((tempDate.compareTo(date))>0){
						iterator.remove();//这行代码是关键,不然在对一个map进行迭代遍历并删除一些符合条件的键值对的时候,容易出现java.util.ConcurrentModificationException 这个异常。
						stopRefreshMap.remove(date);
					}
				}
					
				session.setAttribute("stopRefreshMap"+curPath, stopRefreshMap);
				
				int countNum = stopRefreshMap.get(stopRefreshMap.lastKey()) - stopRefreshMap.get(stopRefreshMap.firstKey());
				//out.println(countNum);
				//判断refreshCount秒内刷新的次数是否超出了指定的次数
				if(countNum >= refreshCount){
					isOverTime = true;
				}
				
				boolean isBlackList = false;
				try{
					if(blackList.trim().length()>0){
						String blackIP = request.getRemoteAddr();
						int position = blackList.indexOf(blackIP);
						if(position != -1){//是否在黑名单中
							Date date = dateFormat.parse(blackList.substring(position+blackIP.length()+1, position+blackIP.length()+21));
							Date newDate2 = new Date(); 
							if(newDate2.getTime()<(date.getTime()+Long.parseLong(blackList.substring(position+blackIP.length()+21, blackList.indexOf(";",position)))*60*1000)){
								isOverTime = true;
								isBlackList = true;
							}
						}					
					}
				}catch (Exception e) {
					e.printStackTrace();
				}
				
				if(isOverTime){
					PrintWriter out = response.getWriter();
					if(isBlackList){
						out.println("<script type=\"text/javascript\">window.location.href='"+blackPage+"'</script>");
					}else{
						out.println(htmlContent);
					}
					out.flush();
					out.close();
					
				}
			}
			
		}else{
			stopRefreshMap = new TreeMap<Date, Integer>();
			stopRefreshMap.put(new Date(), 1);
			session.setAttribute("stopRefreshMap"+curPath, stopRefreshMap);
			
		}
		
		return isOverTime;
	}
	

	public static void main(String args[]) {
		boolean isBlackList = false;
		String blackList = "192.168.158.90,2009-08-04 16:06:00,120;";
		try {
			if (blackList.trim().length() > 0) {
				String blackIP = "192.168.158.90";
				int position = blackList.indexOf(blackIP);
				System.out.println(position);
				if (position != -1) {
					Date date = dateFormat.parse(blackList.substring(position+blackIP.length()+1, position+blackIP.length()+21));
					Date newDate2 = new Date(); 
					if(newDate2.getTime()<(date.getTime()+Long.parseLong(blackList.substring(position+blackIP.length()+21, blackList.indexOf(";",position)))*60*1000)){
						System.out.println("blackIP:" + blackIP);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}


下面的利用Cookie来限制刷新频率,这个是利用了Cookie的最大生命周期来判断刷新次数,不是什么好的办法

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 调用方式:在页面中直接调用下面代码
	StopRefresh stopRefresh = new StopRefresh();
	stopRefresh.limitTime =4;//可以不设置,默认10秒
	stopRefresh.refreshCount=2;//可以不设置,默认5次
	stopRefresh.redirectPage="/index.jsp";////可以不设置,/index.jsp
	stopRefresh.cookieStopRefresh(request,response);

 * @author Administrator
 *
 */
public class StopRefresh {
	
	//刷新的时间段,单位:秒
	public int limitTime = 10;

	//刷新的时间段的最大刷新次数
	public int refreshCount=5;
	
	//超过刷新次数后跳转的页面
	public String redirectPage = "/index.jsp";
/**
	 * 利用Cookie阻止频繁刷新同一页面
	 */
	public void cookieStopRefresh(HttpServletRequest request,HttpServletResponse response) throws IOException{
		PrintWriter out = response.getWriter();
		
		//页面内容
		String htmlContent="<script type=\"text/javascript\">window.location.href='"+redirectPage+"'</script>";
		
		String cookiePath = request.getServletPath();
		Cookie myCookie = null;
		Cookie[] cookies = request.getCookies(); 
		
		//如果cookies为null则创建一个
		if(null == cookies){
			myCookie = new Cookie(cookiePath, "1"); 
			response.addCookie(myCookie);
		}else{
			//取出需要的cookie
			for(int i=0;i<cookies.length;i++){
				if(cookies[i].getName().equalsIgnoreCase(cookiePath)){
					myCookie = cookies[i];
				}
			}
			
			//如果myCookie为null则创建,同时设置cookie的最大生命时长
			if(null == myCookie){
				myCookie = new Cookie(cookiePath, "1"); 
				myCookie.setMaxAge(limitTime);
				response.addCookie(myCookie);
			}else{
				//每刷新一次都设置一次cookie的最大生命时长
				myCookie.setMaxAge(limitTime);
				
				//如果cookieTime内刷新次数大于最大能刷新次数则跳转页面(防止不断刷新),反之刷新次数对应的加1
				if(Integer.parseInt(myCookie.getValue())>=refreshCount){
					out.println(htmlContent);
				}else{
					int count = 1;
					String cookieValue = myCookie.getValue();
					if("".equals(cookieValue)){
						myCookie.setValue(count+"");
						response.addCookie(myCookie);
					}else{
						count = Integer.parseInt(myCookie.getValue())+1;
						myCookie.setValue(count+"");
						response.addCookie(myCookie);
					}
					//out.println(myCookie.getValue());
				}
				//out.println(myCookie.getName());
			}
		}
		out.flush();
		out.close();
	}
	
}




分享到:
评论

相关推荐

    java控制页面刷新频率

    首先,它获取当前时间的时间戳,然后检查session中是否存在"bj"属性,如果存在,则计算当前时间与上次访问时间的差值,如果这个差值小于1500毫秒,则通过注释中的`alert`语句提示用户不要频繁刷新页面,实际上这里...

    网页自动刷新插件

    用户可以根据需求自定义刷新间隔,例如每5秒、每分钟或更长时间,并可以选择是否限制刷新次数。有些高级插件甚至提供了智能刷新模式,例如只有在页面内容更新时才进行刷新,避免了不必要的资源浪费。 以"chromecj....

    网页自动刷新工具.rar

    9. **用户体验**:对于正常用户而言,频繁的页面刷新可能导致页面加载缓慢,影响浏览体验。因此,在设计自动刷新工具时,应考虑如何在刷新和用户体验之间找到平衡。 10. **日志分析**:通过收集和分析刷新操作的...

    防止恶意刷新

    ### 防止恶意刷新——JS与服务器端的联合...然而,值得注意的是,没有任何方法能够完全阻止所有类型的恶意行为,因此建议结合其他安全措施一起使用,如限制IP地址的请求频率、使用验证码等,以提供更全面的安全保障。

    自动刷新网页工具免费版

    同时,它还支持换IP刷新,这对于需要进行网络测试、数据分析或网络投票等场景特别有用,通过更换不同的IP地址,可以避免因为频繁访问同一网页而被服务器识别并限制。此外,刷新失败时的报警功能也是一大亮点,当网页...

    局部刷新导致界面会闪烁的问题

    - **防抖(debounce)和节流(throttle)**:对于频繁触发的事件,如滚动,可以使用防抖或节流技术来限制执行频率,避免连续刷新。 - **虚拟DOM**:使用React等库的虚拟DOM技术,它们可以对比前后状态,只更新真正变化...

    XP打印机连接数限制解决方法

    然而,在某些特定的工作环境中,如打印服务中心或者需要频繁切换打印机的办公室,这个限制就显得过于苛刻了。 解决这个问题的一种方法是通过修改注册表设置。打开注册表编辑器(regedit),导航到以下路径:HKEY_...

    智联简历自动刷新程序

    2. 配置合理性:合理设置刷新频率,既不能过于频繁以免触发平台限制,也不能间隔过长影响简历的曝光。 3. 账号保护:不要在公共场所或不安全的网络环境下使用,以防账号信息泄露。 4. 更新维护:定期检查程序是否有...

    php防止CC攻击代码 php防止网页频繁刷新

    这种方法可以通过限制重复提交来防止无意义的频繁刷新和请求。 3. 防止网页频繁刷新的PHP代码实现: 提供的PHP代码实现了一个简单的防止页面在3秒内刷新超过5次的功能。原理是使用session记录页面最后一次访问的...

    防刷新代码.

    在IT行业中,"防刷新代码"是一个重要的概念,主要用于防止用户或恶意脚本频繁地刷新网页,从而保护服务器资源和提升用户体验。防刷新代码通常应用于票务系统、抢购平台等高并发场景,以避免资源被瞬间大量请求,导致...

    php_防刷新网页计数器count

    在PHP编程中,防止网页被用户频繁刷新是提高网站性能和用户体验的重要环节。"php_防刷新网页计数器count"是一个这样的解决方案,它旨在记录并限制用户在短时间内重复访问同一页面的次数,以避免不必要的资源消耗和...

    定时刷新页面

    - **跨域限制**:如果页面涉及跨域请求,频繁刷新可能导致安全策略上的问题,如CORS(跨源资源共享)问题,需注意处理。 通过上述分析,我们可以看到,使用JavaScript实现定时刷新页面是一个既简单又复杂的过程。它...

    javascript刷新父页面

    3. **用户体验**:在设计交互时,要考虑用户的体验,避免频繁刷新导致数据丢失或其他不良影响。 #### 六、总结 通过本文的学习,我们了解了如何在JavaScript中刷新父窗口页面的方法,以及这些方法的具体实现细节。...

    刷新是不可能刷新的这辈子不可能刷新的

    在某些场景下,开发者可能需要控制页面的刷新行为,比如在游戏、表单提交或者在线支付等过程中,频繁或意外的刷新会导致数据丢失或用户体验下降。本文将深入探讨JavaScript如何处理页面刷新以及相关的编程技巧。 ...

    php防恶意刷新,过度抓取页面脚本

    当用户或第三方程序恶意地频繁刷新页面或过度抓取内容时,这可能导致服务器资源耗尽,影响正常用户的访问,甚至可能暴露敏感信息。针对这种情况,PHP作为广泛应用的服务器端脚本语言,提供了多种策略来防止这种恶意...

    h5单页面上拉刷新下拉加载

    在H5应用中,上拉刷新和下拉加载是提高用户体验的重要功能,尤其在移动设备上,...在开发过程中,需要考虑性能优化,如使用节流或防抖函数来限制滚动事件的频繁触发,以及合理安排数据加载时机,确保流畅的用户体验。

    js短信验证码倒计时(页面刷新无效)

    在网页开发中,短信验证码是验证用户身份的重要手段,它通常与倒计时功能结合,以防止用户频繁发送验证码,减轻服务器压力,并提供良好的用户体验。本文将深入探讨如何实现一个js短信验证码倒计时功能,同时确保在...

    jsp刷新不变计数器

    7. **性能优化**:频繁的计数器更新可能对数据库造成压力。可以考虑批量更新,例如每达到一定数量的访问再统一增加计数。 8. **安全问题**:公开暴露的计数器可能会遭受恶意攻击,如刷页面来提高计数。可以通过IP...

    html5页面上拉刷新

    1. **节流和防抖**:为了避免用户快速滚动时频繁触发滚动事件处理函数,可以使用节流(throttle)或防抖(debounce)技术来限制事件的执行频率。 2. **延迟加载**:对于大数据量的列表,可以采用懒加载策略,只在...

    下拉刷新功能的源代码,jQuery模拟原生态App 上拉刷新 下拉加载 效果代码.zip

    - **节流与防抖**:为了防止频繁触发事件,可以使用节流(throttle)或防抖(debounce)技术来限制事件处理函数的执行频率。 - **异步优化**:避免阻塞用户界面,使用异步加载并在回调中更新页面。 - **缓存DOM...

Global site tag (gtag.js) - Google Analytics