拦截器实现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被锁时间

实体类

public class BlackList {

    private int id;
private String ip;
private Date iptime; // 日期类型,格式:yyyy-MM-dd HH:mm:ss
//构造器
public BlackList() {
} public BlackList(String ip, Date iptime) {
this.ip = ip;
this.iptime = iptime;
}
// get && set 方法
}

Dao层

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

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

实现 HandlerInterceptor 接口

public class URLInterceptor implements HandlerInterceptor {

    @Autowired
BlackListDao blackListDao; private Map<String, Integer> redisTemplate = new HashMap<String, Integer>();
private static final Logger logger = LoggerFactory.getLogger(URLInterceptor.class); //在请求处理之前进行调用(Controller方法调用之前)
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
return true;
} //请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
String ip = IPAddressUtil.getClientIpAddress(httpServletRequest);
List<BlackList> blackLists = blackListDao.findByIp(ip);
if (blackLists == null || blackLists.size() == 0){
urlHandle(httpServletRequest, 5000, 10);
} else {
//强制控制跳转
modelAndView.setViewName("/errorpage/error.html");
}
} //在整个请求结束之后被调用
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } public void urlHandle(HttpServletRequest request, long limitTime,int limitCount) throws RequestLimitException {
/**
* 省略业务逻辑部分,参考"准备"步骤
*/
if (count > limitCount){ //符合锁定条件
Calendar calendar = Calendar.getInstance();
Date iptime=calendar.getTime();
BlackList blackList = new BlackList(ip, iptime);
blackListDao.addBlackList(blackList);
throw new RequestLimitException();
}
}
}

WebMvcConfigurerAdapter类

配置 spring mvc的拦截器 WebMvcConfigurerAdapter。

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

Controller类

    @RequestMapping("/url/test")
@ResponseBody
public String URLtest() {
return "success";
}

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. 01: 重写Django admin

    目录: 1.1 重写Django admin项目各文件作用# 1.2 重写Django admin用户认证 1.3 将要显示的表注册到我们自己的kind_admin.py中 1.4 项目首页:显示注册 ...

  2. 如何写出安全的 API 接口?接口参数加密签名设计思路

    原文链接:http://blog.csdn.net/ma_jiang/article/details/53636840

  3. 20145336张子扬《网络对抗》MSF基础应用

    20145336张子扬 <网络对抗>MSF基础应用 实验一:主动攻击,利用ms08_067漏洞进行攻击 首先使用use exploit/windows/smb/ ms08_067 _net ...

  4. 20135234mqy-——信息安全系统设计基础第九周学习总结

    第十章 系统级I/O 10.1 Unix I/O 一个Unix文就是一个m个字节的序列 Unix:将设备映射为文件的方式,允许Unix内核引出一个简单低级的应用接口 能够使得所有输入输出都能以一种统一 ...

  5. .Net Core集成Office Web Apps(一)

    最近开始学习.Net Core,并使用Visual Studio Code工具来开发.感觉开发起来特别的方便,但是有个头疼的地方:许多的类库被修改了,一时半会儿还熟悉不了,需要查阅官方API... M ...

  6. Ubuntu Eclipse ns3编译中 遇到的OSError 系列问题

    问题1:Permission denied 解决方法:修改文件权限,利用 chmod 命令 修改在 /home/wasdns/workspace/MyNS3_Mac/ns-3.25 (eclipse工 ...

  7. UVa 12545 比特变换器

    https://vjudge.net/problem/UVA-12545 题意:输入两个等长的串S和T,其中S包含字符0,1,?,但T只包含0和1. 用尽量少的步数把S变成T.每步有3种操作: ①把S ...

  8. C++中的也能使用正则表达式----转载

    转自:https://www.cnblogs.com/ittinybird/p/4853532.html, 以作笔记. 正则表达式Regex(regular expression)是一种强大的描述字符 ...

  9. spoj MINSUB 单调栈+二分

    题目链接:点击传送 MINSUB - Largest Submatrix no tags  You are given an matrix M (consisting of nonnegative i ...

  10. 基于贝叶斯优化的超参数tuning

    https://arimo.com/data-science/2016/bayesian-optimization-hyperparameter-tuning/ 贝叶斯优化:使用高斯过程作为代理函数, ...