拦截器实现IP黑名单

前言

最近一直在搞 Hexo+GithubPage 搭建个人博客,所以没怎么进行 SpringBoot 的学习。所以今天就将上次的”?秒防刷新”进行了一番修改。上次是采用注解加拦截器(@Aspect)来实现功能的。但是,如果需求是一个全局的拦截器对于大部分URL都进行拦截的话,自己一个个加显然是不可能的。而且上次的拦截器对于Controller的参数有所要求,在实际他人引用总是显得不方便。所以,这次使用了继承HandlerInterceptor来实现拦截器。

功能需求

对于项目中某类URL进行拦截,若用户在短时间内大量访问该链接,则将用户IP列入黑名单,禁止用户访问网页。(同时,可以使用@Async来创建定时任务帮用户解禁。)

准备

?秒防刷新的业务逻辑

博客地址 : http://blog.csdn.net/u011244202/article/details/54783337
项目参考地址 : https://github.com/FunriLy/springboot-study/tree/master/%E6%A1%88%E4%BE%8B5

SpringBoot+Druid+MyBatis

博客地址 : http://blog.csdn.net/u011244202/article/details/54709060
项目参考地址 : https://github.com/FunriLy/springboot-study/tree/master/%E6%A1%88%E4%BE%8B1

知识记录

Spring 的拦截器
HandlerInterceptor 的功能跟过滤器类似,但是提供更精细的的控制能力:在request被响应之前、request被响应之后、视图渲染之前以及request全部结束之后。我们不能通过拦截器修改request内容,但是可以通过抛出异常(或者返回false)来暂停request的执行。

配置拦截器也很简单,Spring 为此提供了基础类WebMvcConfigurerAdapter ,我们只需要重写addInterceptors 方法添加注册拦截器。

实现自定义拦截器只需要3步:
1、创建我们自己的拦截器类并实现 HandlerInterceptor 接口。
2、创建一个 Java 类继承 WebMvcConfigurerAdapter,并重写 addInterceptors 方法。
3、实例化我们自定义的拦截器,然后将对像手动添加到拦截器链中(在addInterceptors方法中添加)。

正式开工

IP工具类

由于不清楚用户代理,最好能使用一个工具类来来获取用户真实IP。这个Google就能找到,我就不贴代码了。

数据库

我使用的是MySQL数据库,持久层框架为MyBatis。具体可参考”准备”步骤。
我在”myboot”数据库中创建一张表”blaclist”,属性如下:

字段名 解释
id 记录的id
ip 用户真实IP
iptime IP被锁时间

实体类

  1. public class BlackList {
  2.  
  3. private int id;
  4. private String ip;
  5. private Date iptime; // 日期类型,格式:yyyy-MM-dd HH:mm:ss
  6. //构造器
  7. public BlackList() {
  8. }
  9.  
  10. public BlackList(String ip, Date iptime) {
  11. this.ip = ip;
  12. this.iptime = iptime;
  13. }
  14. // get && set 方法
  15. }

Dao层

注意XML配置与对应实体配置(省略)。

  1. @Mapper
  2. public interface BlackListDao {
  3. // 根据IP来查找记录
  4. List<BlackList> findByIp(String ip);
  5. // 添加记录
  6. int addBlackList(@Param("blackList") BlackList blackList);
  7. }

实现 HandlerInterceptor 接口

  1. public class URLInterceptor implements HandlerInterceptor {
  2.  
  3. @Autowired
  4. BlackListDao blackListDao;
  5.  
  6. private Map<String, Integer> redisTemplate = new HashMap<String, Integer>();
  7. private static final Logger logger = LoggerFactory.getLogger(URLInterceptor.class);
  8.  
  9. //在请求处理之前进行调用(Controller方法调用之前)
  10. @Override
  11. public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
  12. return true;
  13. }
  14.  
  15. //请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
  16. @Override
  17. public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
  18. String ip = IPAddressUtil.getClientIpAddress(httpServletRequest);
  19. List<BlackList> blackLists = blackListDao.findByIp(ip);
  20. if (blackLists == null || blackLists.size() == 0){
  21. urlHandle(httpServletRequest, 5000, 10);
  22. } else {
  23. //强制控制跳转
  24. modelAndView.setViewName("/errorpage/error.html");
  25. }
  26. }
  27.  
  28. //在整个请求结束之后被调用
  29. @Override
  30. public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
  31.  
  32. }
  33.  
  34. public void urlHandle(HttpServletRequest request, long limitTime,int limitCount) throws RequestLimitException {
  35. /**
  36. * 省略业务逻辑部分,参考"准备"步骤
  37. */
  38. if (count > limitCount){ //符合锁定条件
  39. Calendar calendar = Calendar.getInstance();
  40. Date iptime=calendar.getTime();
  41. BlackList blackList = new BlackList(ip, iptime);
  42. blackListDao.addBlackList(blackList);
  43. throw new RequestLimitException();
  44. }
  45. }
  46. }

WebMvcConfigurerAdapter类

配置 spring mvc的拦截器 WebMvcConfigurerAdapter。

  1. @Configuration
  2. public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {
  3.  
  4. @Bean //把我们的拦截器注入为bean
  5. public HandlerInterceptor getMyInterceptor(){
  6. return new URLInterceptor();
  7. }
  8.  
  9. @Override
  10. public void addInterceptors(InterceptorRegistry registry) {
  11. // 多个拦截器组成一个拦截器链
  12. // addPathPatterns 用于添加拦截规则, 这里假设拦截 /url 后面的全部链接
  13. // excludePathPatterns 用户排除拦截
  14. registry.addInterceptor(getMyInterceptor()).addPathPatterns("/url/**");
  15. super.addInterceptors(registry);
  16. }
  17. }

Controller类

  1. @RequestMapping("/url/test")
  2. @ResponseBody
  3. public String URLtest() {
  4. return "success";
  5. }

spring boot 学习(十二)拦截器实现IP黑名单的更多相关文章

  1. springMVC学习 十二 拦截器

    一 拦截器概述 拦截器技术比较像java web技术中的过滤器技术,都是发送 请求时被拦截器拦截,在控制器的前后添加额外功能.但是和Spring中的Aop技术是由区别的.AOP 在特定方法前后扩充(一 ...

  2. spring boot / cloud (十二) 异常统一处理进阶

    spring boot / cloud (十二) 异常统一处理进阶 前言 在spring boot / cloud (二) 规范响应格式以及统一异常处理这篇博客中已经提到了使用@ExceptionHa ...

  3. Spring Boot学习记录(二)--thymeleaf模板 - CSDN博客

    ==他的博客应该不错,没有细看 Spring Boot学习记录(二)--thymeleaf模板 - CSDN博客 http://blog.csdn.net/u012706811/article/det ...

  4. Springboot拦截器实现IP黑名单

    Springboot拦截器实现IP黑名单 一·业务场景和需要实现的功能 以redis作为IP存储地址实现. 业务场景:针对秒杀活动或者常规电商业务场景等,防止恶意脚本不停的刷接口. 实现功能:写一个拦 ...

  5. spring boot 学习(十四)SpringBoot+Redis+SpringSession缓存之实战

    SpringBoot + Redis +SpringSession 缓存之实战 前言 前几天,从师兄那儿了解到EhCache是进程内的缓存框架,虽然它已经提供了集群环境下的缓存同步策略,这种同步仍然需 ...

  6. Spring Boot使用过滤器和拦截器分别实现REST接口简易安全认证

    本文通过一个简易安全认证示例的开发实践,理解过滤器和拦截器的工作原理. 很多文章都将过滤器(Filter).拦截器(Interceptor)和监听器(Listener)这三者和Spring关联起来讲解 ...

  7. Spring Boot 优雅的配置拦截器方式

    https://my.oschina.net/bianxin/blog/2876640 https://cs.xieyonghui.com/java/55.html 其实spring boot拦截器的 ...

  8. Spring Boot学习笔记二

    Spring Boot入门第二篇 第一天的详见:https://www.cnblogs.com/LBJLAKERS/p/12001253.html 同样是新建一个pring Initializer快速 ...

  9. Springboot 系列(六)Spring Boot web 开发之拦截器和三大组件

    1. 拦截器 Springboot 中的 Interceptor 拦截器也就是 mvc 中的拦截器,只是省去了 xml 配置部分.并没有本质的不同,都是通过实现 HandlerInterceptor ...

随机推荐

  1. 03: JavaScript基础

    目录: 参考W3school 1.1 变量 1.2 JavaScript中数据类型 1.3 JavaScript中的两种for循环 1.4 条件语句:if.switch.while 1.5 break ...

  2. linux虚拟机中安装vm_tool的方法及用处

    解决问题:实现虚拟机VMware上linux与windows互相自由复制与粘贴.如在同一个系统下ctrl+c 与ctrl+v一样方便.解决了只能通过U盘摆渡复制的繁琐问题. 系统环境: 虚拟机VMwa ...

  3. GitHub Desktop离线安装包

    GitHub Desktop离线安装包.上传时间是2017-02-05 版本3.3.4.0,Git shell版本是v2.11.0. 百度网盘的下载链接: http://pan.baidu.com/s ...

  4. 20145122《Java面向对象程序设计》实验二实验报告

    实验名称: Java面向对象程序设计 实验内容: 初步掌握单元测试和TDD 理解并掌握面向对象三要素:封装.继承.多态 初步掌握UML建模 熟悉S.O.L.I.D原则 了解设计模式 PSP时间 步骤 ...

  5. 20145330 《网络对抗》 Eternalblue(MS17-010)漏洞复现与S2-045漏洞的利用及修复

    20145330 <网络对抗> Eternalblue(MS17-010)漏洞利用工具实现Win 7系统入侵与S2-045漏洞的利用及修复 加分项目: PC平台逆向破解:注入shellco ...

  6. Python3基础 函数 递归 阶乘与斐波那契数列

             Python : 3.7.0          OS : Ubuntu 18.04.1 LTS         IDE : PyCharm 2018.2.4       Conda ...

  7. 【TCP/IP详解 卷一:协议】TCP的小结

    前言:TCP学习的综述 在学习TCP/IP协议的大头:TCP协议 的过程中,遇到了很多机制和知识点,详解中更是用了足足8章的内容介绍它. TCP协议作为 应用层 和 网络层 中间的 传输层协议,既要为 ...

  8. Apache+Php+Mariadb+NFS+discuz

    安装LAMP服务器,并利用discuz做测试 nfs + discuz      192.168.108.158 php + DNS        192.168.108.160 apache     ...

  9. hdu 4352 XHXJ's LIS 数位dp+状态压缩

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4352 XHXJ's LIS Time Limit: 2000/1000 MS (Java/Others ...

  10. ubuntu 14.04 (desktop amd 64) 下载

    http://cdimage.ubuntu.com/ubuntukylin/releases/14.04/release/