四十九、SpingBoot引入第三方filter

2024-05-10 21:38

本文主要是介绍四十九、SpingBoot引入第三方filter,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

最近手头活不多,被其他项目拉去帮忙。他们的需求是,项目中需要加入第三方的过滤器(用于单点登录认证的),项目采用的是spring boot,spring boot之前没深入玩过,所以费了些时间。

需求:

    第三方提供了一个filter以及使用标准web.xml时的配置方法,要求整合到项目中

过程:

    第一步:

    作为不百度(google)不会写代码的程序员,第一反应是去baidu一下,毕竟spring boot的使用停留在写web api的码砖水平上。百度结果,大部分都是用类似下面的方法:

    @Beanpublic FilterRegistrationBean pluginFilter(){//将第三方filter实例,配置信息设置到一个FilterRegistrationBean中//详细代码省略,网上到处都是}

    优点在于:简单。

    缺点:这种第三方的filter,如果是多个的,每个都得重新加这种方法,对于扩展来说,啰嗦

 

    于是,寻求spring boot项目直接使用web.xml里过滤器配置的方案,百度了好些,都是直接将spring boot项目变为使用web.xml配置的,这个动作有点大,怕把项目给搞乱了,没敢采用。。。

 

     第二步:

     目标明确为,使用Bean标签返回FilterRegistrationBean(或类似的接口实例)的方向,但是这个Bean要能将多个过滤器注册给spring。稍微读了一下源码,发现FilterRegistrationBean这个鬼,这正起作用的是定义在AbstractFilterRegistrationBean中的方法onStartup方法

public void onStartup(ServletContext servletContext) throws ServletException {Filter filter = this.getFilter();Assert.notNull(filter, "Filter must not be null");String name = this.getOrDeduceName(filter);if (!this.isEnabled()) {this.logger.info("Filter " + name + " was not registered (disabled)");} else { Dynamic added = servletContext.addFilter(name, filter);if (added == null) {this.logger.info("Filter " + name + " was not registered (possibly already registered?)");} else {this.configure(added);}}
}

    所以,咱们重写一下这个onStartup方法(类名后缀用的proxy可能不太合适,请不要在意细节):

package com.xxx.common.filter;import org.dom4j.Document;
import org.dom4j.Element;
import org.springframework.boot.web.servlet.FilterRegistrationBean;import javax.servlet.Filter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;public class XxxFilterRegistrationBeanProxy extends FilterRegistrationBean{private Document plugin_xml = null;//所有需要注册的filterprivate Map<String,FilterRegistrationBean> filterRegistrationBeans;public IdssFilterRegistrationBeanProxy() {}public Document getPlugin_xml() {return plugin_xml;}public void setPlugin_xml(Document plugin_xml) {this.plugin_xml = plugin_xml;}public IdssFilterRegistrationBeanProxy(Document plugin_xml) throws IllegalAccessException, InstantiationException, ClassNotFoundException {super();this.plugin_xml = plugin_xml;setFilterRegistrationBeans();}@Overridepublic void onStartup(ServletContext servletContext) throws ServletException {if(filterRegistrationBeans == null || filterRegistrationBeans.size()==0) return;//执行实际的FilterRegistrationBean的onStartup方法for(FilterRegistrationBean bean : filterRegistrationBeans.values()){bean.onStartup(servletContext);}}private void setFilterRegistrationBeans() throws ClassNotFoundException, IllegalAccessException, InstantiationException {//读取xml配置文件,实例化FilterRegistrationBeanif(plugin_xml == null) return;filterRegistrationBeans = new HashMap<>();Element root = plugin_xml.getRootElement();Iterator<Element> filter_roots = root.elementIterator("filter");int order = 0;while (filter_roots.hasNext()){order++;Element filter_root = filter_roots.next();String filter_name = filter_root.elementText("filter-name").trim();String class_name = filter_root.elementText("filter-class").trim();Filter filter = (Filter) Class.forName(class_name).newInstance();FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();filterRegistrationBean.setFilter(filter);filterRegistrationBean.setName(filter_name);filterRegistrationBean.setOrder(order);Iterator<Element> parm_settings = filter_root.elementIterator("init-param");while (parm_settings.hasNext()){Element parm = parm_settings.next();filterRegistrationBean.addInitParameter(parm.elementText("param-name").trim(),parm.elementText("param-value").trim());}filterRegistrationBeans.put(filter_name,filterRegistrationBean);}Iterator<Element> filter_mappings = root.elementIterator("filter-mapping");while (filter_mappings.hasNext()){Element filter_mapping = filter_mappings.next();String filter_name = filter_mapping.elementText("filter-name");if(filterRegistrationBeans.containsKey(filter_name)){filterRegistrationBeans.get(filter_name).addUrlPatterns(filter_mapping.elementText("url-pattern"));}}}
}

注入spring boot的单例类中,给出一个Bean注解的方法,返回上面类的实例

package com.xxx.common.filter;import com.xxx.common.utils.PropertyUtil;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStreamReader;@Component
public class XxxPluginFilter {private XxxFilterRegistrationBeanProxy XxxFilterRegistrationBeanProxy = new XxxFilterRegistrationBeanProxy();private Document plugin_xml = null;private final static String plugin_filter_path = PropertyUtil.getProperty("plugin_filter_path");@Beanpublic FilterRegistrationBean pluginFilter(){return XxxFilterRegistrationBeanProxy;}@PostConstructprivate void init() throws IllegalAccessException, InstantiationException, ClassNotFoundException {if(plugin_filter_path == null || plugin_filter_path.isEmpty()) return;SAXReader reader = new SAXReader();InputStreamReader inputStreamReader = null;try {inputStreamReader = new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream(plugin_filter_path));plugin_xml = reader.read(inputStreamReader);xxxFilterRegistrationBeanProxy = new XxxFilterRegistrationBeanProxy(plugin_xml);} catch (DocumentException e) {e.printStackTrace();} finally {if(inputStreamReader != null) {try {inputStreamReader.close();} catch (IOException e) {e.printStackTrace();}}}}
}

filter的xml配置文件示例:

<?xml version="1.0" encoding="UTF-8"?>
<plugin-filter><filter><filter-name>filter1</filter-name><filter-class>com.test.Filter1</filter-class><init-param><param-name>servername</param-name><param-value>http://localhost:8081</param-value></init-param></filter><filter><filter-name>filter2</filter-name><filter-class>com.test.Filter2</filter-class><init-param><param-name>initteset</param-name><param-value>yyyy</param-value></init-param></filter><filter-mapping><!-- 需要过滤的路径和文件类型 --><filter-name>filter1</filter-name><url-pattern>/*</url-pattern></filter-mapping><filter-mapping><filter-name>filter2</filter-name><url-pattern>/api/*</url-pattern></filter-mapping>
</plugin-filter>

简单粗暴而有效

这篇关于四十九、SpingBoot引入第三方filter的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/977633

相关文章

java对接第三方接口的三种实现方式

《java对接第三方接口的三种实现方式》:本文主要介绍java对接第三方接口的三种实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录HttpURLConnection调用方法CloseableHttpClient调用RestTemplate调用总结在日常工作

Spring Boot拦截器Interceptor与过滤器Filter深度解析(区别、实现与实战指南)

《SpringBoot拦截器Interceptor与过滤器Filter深度解析(区别、实现与实战指南)》:本文主要介绍SpringBoot拦截器Interceptor与过滤器Filter深度解析... 目录Spring Boot拦截器(Interceptor)与过滤器(Filter)深度解析:区别、实现与实

CSS引入方式和选择符的讲解和运用小结

《CSS引入方式和选择符的讲解和运用小结》CSS即层叠样式表,是一种用于描述网页文档(如HTML或XML)外观和格式的样式表语言,它主要用于将网页内容的呈现(外观)和结构(内容)分离,从而实现... 目录一、前言二、css 是什么三、CSS 引入方式1、行内样式2、内部样式表3、链入外部样式表四、CSS 选

gradle第三方Jar包依赖统一管理方式

《gradle第三方Jar包依赖统一管理方式》:本文主要介绍gradle第三方Jar包依赖统一管理方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录背景实现1.顶层模块build.gradle添加依赖管理插件2.顶层模块build.gradle添加所有管理依赖包

Maven中引入 springboot 相关依赖的方式(最新推荐)

《Maven中引入springboot相关依赖的方式(最新推荐)》:本文主要介绍Maven中引入springboot相关依赖的方式(最新推荐),本文给大家介绍的非常详细,对大家的学习或工作具有... 目录Maven中引入 springboot 相关依赖的方式1. 不使用版本管理(不推荐)2、使用版本管理(推

Java学习手册之Filter和Listener使用方法

《Java学习手册之Filter和Listener使用方法》:本文主要介绍Java学习手册之Filter和Listener使用方法的相关资料,Filter是一种拦截器,可以在请求到达Servl... 目录一、Filter(过滤器)1. Filter 的工作原理2. Filter 的配置与使用二、Listen

springboot filter实现请求响应全链路拦截

《springbootfilter实现请求响应全链路拦截》这篇文章主要为大家详细介绍了SpringBoot如何结合Filter同时拦截请求和响应,从而实现​​日志采集自动化,感兴趣的小伙伴可以跟随小... 目录一、为什么你需要这个过滤器?​​​二、核心实现:一个Filter搞定双向数据流​​​​三、完整代码

在React中引入Tailwind CSS的完整指南

《在React中引入TailwindCSS的完整指南》在现代前端开发中,使用UI库可以显著提高开发效率,TailwindCSS是一个功能类优先的CSS框架,本文将详细介绍如何在Reac... 目录前言一、Tailwind css 简介二、创建 React 项目使用 Create React App 创建项目

Python实现无痛修改第三方库源码的方法详解

《Python实现无痛修改第三方库源码的方法详解》很多时候,我们下载的第三方库是不会有需求不满足的情况,但也有极少的情况,第三方库没有兼顾到需求,本文将介绍几个修改源码的操作,大家可以根据需求进行选择... 目录需求不符合模拟示例 1. 修改源文件2. 继承修改3. 猴子补丁4. 追踪局部变量需求不符合很

一文教你Python引入其他文件夹下的.py文件

《一文教你Python引入其他文件夹下的.py文件》这篇文章主要为大家详细介绍了如何在Python中引入其他文件夹里的.py文件,并探讨几种常见的实现方式,有需要的小伙伴可以根据需求进行选择... 目录1. 使用sys.path动态添加路径2. 使用相对导入(适用于包结构)3. 使用pythonPATH环境