1、定义过滤器

package cn.study.filter;import java.io.IOException;
import java.util.Optional;import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;public class MyFilter implements Filter {@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpServletRequest httpReq = (HttpServletRequest) request;HttpServletResponse httpResp = (HttpServletResponse) response;// 判断条件boolean condition = ... ;if (!condition) {httpResp.sendError(401);} else {chain.doFilter(request, response);}}
}

2、添加过滤器

package cn.study.config;import cn.study.filter.MyFilter;import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import java.util.HashSet;
import java.util.Set;@Configuration
public class WebMvcConfig implements WebMvcConfigurer {@Beanpublic FilterRegistrationBean<MyFilter> registration() {Set<String> pathSet = new HashSet<>();FilterRegistrationBean<MyFilter> filterRegistrationBean = new FilterRegistrationBean<>();filterRegistrationBean.setFilter(new MyFilter());pathSet.forEach(path -> filterRegistrationBean.addUrlPatterns(path));filterRegistrationBean.setName("MyFilter");filterRegistrationBean.setOrder(1);return filterRegistrationBean;}
}

3、只用将上述代码中的pathSet替换成需要过滤的路径集合,功能就实现了,下面介绍两种获取方式,可以直接在WebMvcConfig中添加

package cn.study.config;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;@Configuration
public class WebMvcConfig implements WebMvcConfigurer {@AutowiredWebApplicationContext applicationContext;/*** */public Set<String> getControllerPathSet1() {Set<String> pathSet = new HashSet<String>();RequestMappingHandlerMapping handlerMapping = applicationContext.getBean(RequestMappingHandlerMapping.class);handlerMapping.getHandlerMethods().values().forEach(handlerMethod -> {Class<?> clazz = handlerMethod.getMethod().getDeclaringClass();if (clazz.getName().startsWith("cn.study")) {RequestMapping annotation = clazz.getAnnotation(RequestMapping.class);if (annotation != null) {Arrays.asList(annotation.value()).forEach(value -> pathSet.add(value + "/*"));}}});return pathSet;}/*** */public Set<String> getControllerPathSet2() {String packageName = "cn.study";Set<String> pathSet = new HashSet<>();String packageDirName = packageName.replace('.', '/');try {URL url = Thread.currentThread().getContextClassLoader().getResource(packageDirName);String protocol = url.getProtocol();if ("file".equals(protocol)) {String filePath = URLDecoder.decode(url.getFile(), "UTF-8");getControllerPath(packageName, filePath, pathSet);}} catch (IOException e) {e.printStackTrace();}return pathSet;}private void getControllerPath(String packageName, String packagePath, Set<String> pathSet) {File dir = new File(packagePath);if (!dir.exists() || !dir.isDirectory()) {return;}File[] dirfiles = dir.listFiles(file -> (file.isDirectory()) || (file.getName().endsWith("Controller.class")));for (File file : dirfiles) {if (file.isDirectory()) {getControllerPath(packageName + "." + file.getName(), file.getAbsolutePath(), pathSet);} else {String className = file.getName().substring(0, file.getName().length() - 6);try {Class<?> clazz = Class.forName(packageName + '.' + className);RequestMapping annotation = clazz.getAnnotation(RequestMapping.class);if (annotation != null) {Arrays.asList(annotation.value()).forEach(value -> pathSet.add(value + "/*"));}} catch (ClassNotFoundException e) {e.printStackTrace();}}}}
}

4、第一种方法使用Spring自带的方法更通用一些,第二种要求所有controller必须以Controller作为结尾

参考文章1:https://www.cnblogs.com/Leechg/p/10058763.html

参考文章2:https://blog.csdn.net/tt____tt/article/details/82012999

动态为Spring Boot项目中所有自定义的Controller添加过滤器的两种方法相关推荐

  1. 多个html如何套用套一个头部,Vue.js项目中管理每个页面的头部标签的两种方法...

    在 Vue SPA 应用中,如果想要修改 HTML 的头部标签,如页面的 title ,我们只能去修改 index.html 模板文件,但是这个是全局的修改,如何为每个页面都设置不一样的 title ...

  2. 怎样在python的turtle中输入文字_Python在图片中添加文字的两种方法

    本文主要介绍的是利用Python在图片中添加文字的两种方法,下面分享处理供大家参考学习,下来要看看吧 一.使用OpenCV 在图片中添加文字看上去很简单,但是如果是利用OpenCV来做却很麻烦.Ope ...

  3. spring boot 项目源码_Spring Boot2 系列教程(三)理解 Spring Boot 项目中的 parent

    前面和大伙聊了 Spring Boot 项目的三种创建方式,这三种创建方式,无论是哪一种,创建成功后,pom.xml 坐标文件中都有如下一段引用: <parent><groupId& ...

  4. 在Spring Boot项目中使用Spock框架

    转载:https://www.jianshu.com/p/f1e354d382cd Spock框架是基于Groovy语言的测试框架,Groovy与Java具备良好的互操作性,因此可以在Spring B ...

  5. scheduled每天下午1点执行一次_在Spring Boot项目中使用@Scheduled注解实现定时任务...

    在java开发中定时任务的实现有多种方式,jdk有自己的定时任务实现方式,很多框架也有定时任务的实现方式.这里,我介绍一种很简单的实现方式,在Spring Boot项目中使用两个注解即可实现. 在sp ...

  6. Spring Boot 项目中Java对象的字符串类型属性值转换为JSON对象的布尔类型键值的解决方法及过程

    文章目录 场景描述 示例说明 解决历程 @JsonFormat是否能解决问题? 万能方案-调试 替代方案 补充知识 Java对象与JSON对象的序列化与反序列化 相关注解说明 后记 场景描述 在Spr ...

  7. Spring Boot项目中使用RestTemplate调用https接口出现 unable to find valid certification path to requested target

    问题描述:Spring Boot项目中使用RestTemplate调用https接口出现以下错误: PKIX path building failed: sun.security.provider.c ...

  8. Spring Boot项目中集成Elasticsearch,并实现高效的搜索功能

    Spring Boot项目中集成Elasticsearch 前言 环境准备 引入依赖 配置Elasticsearch连接信息 定义实体类 定义Elasticsearch操作接口 实现搜索功能 总结 前 ...

  9. 怎么在python中添加文字_Python在图片中添加文字的两种方法

    本文主要介绍的是利用Python在图片中添加文字的两种方法,下面分享处理供大家参考学习,下来要看看吧 一.使用OpenCV 在图片中添加文字看上去很简单,但是如果是利用OpenCV来做却很麻烦.Ope ...

  10. java整型转换为数组_基于java中byte数组与int类型的转换(两种方法)

    java中byte数组与int类型的转换,在网络编程中这个算法是最基本的算法,我们都知道,在socket传输中,发送.者接收的数据都是 byte数组,但是int类型是4个byte组成的,如何把一个整形 ...

最新文章

  1. 面试题:函数回调机制、异步函数回调机制图例详解 没毛用
  2. mysql使用索引为什么查询速度变快很多?
  3. springboot2.1.5集成finereport10.0过程中:手动安装本地jar包到maven仓库
  4. 频率学派还是贝叶斯学派?聊一聊机器学习中的MLE和MAP
  5. shell习题第8题:监控nginx的502状态
  6. Fiddler4的下载与安装
  7. css文字加边框镂空文字_如何使用CSS创建镂空边框设计
  8. 网站推广教程(SEO,优化)100条
  9. STK10与MATLAB互联
  10. 标梵互动信息解说关于CSS-in-JS: 使用及优缺点
  11. windows7 配置php开发环境
  12. 技术面试要做哪些准备?
  13. 微信公众号文章爬取下载各种格式
  14. 第4.2章:StarRocks数据导出--Export
  15. 看程序员奶爸是如何通过代码给宝宝起名的~
  16. 【服务器数据恢复】服务器reiserfs文件系统损坏的数据恢复案例
  17. 微服务和分布式和SpringCloud三者的关系
  18. 马斯克大力推荐Starlink新品:价格更高,网速更慢???
  19. 使用C语言+EasyX完成消灭星星游戏(1)
  20. stm32 mbed实现openmv追踪小车

热门文章

  1. 计算机控制plc应用论文,PLC自动控制系系统在变频器中的运用
  2. html想实现文字环绕图片,HTML/CSS实现文字环绕图片布局
  3. Golang工程师历年企业笔试真题汇总
  4. psd文件转响应式html5,前端开发/前端切图/PSD转HTML/响应式HTML5
  5. Regular DLL
  6. 文本数据挖掘(Text Mining)
  7. ipa文件怎么安装到iPhone iPhone怎么安装ipa
  8. 排雷日记 -- mybatisplus分页查询效率
  9. 电脑键盘部分按键失灵_方法 | 键盘按键部分失灵,怎么办?
  10. ANSYS Electromagnetics Suite 2022 R2 软件下载与安装教程