如何解析SpringBoot2快速整合Filter过程


如何解析SpringBoot2快速整合Filter过程,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

概述

SpringBoot 中没有 web.xml, 我们无法按照原来的方式在 web.xml 中配置 Filter 。但是我们可以通过 JavaConfig(@Configuration +@Bean)方式进行配置。通过FilterRegistrationBean 将自定义 Filter 添加到 SpringBoot 的过滤链中。

实战操作

实战操作通过定义一个拦截所有访问项目的URL的 Filter来进行演示的。

首先定义一个统一访问 URL 拦截的 Filter。代码如下:

public class UrlFilter implements Filter {  private Logger log = LoggerFactory.getLogger(UrlFilter.class);  @Override  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)      throws IOException, ServletException {  HttpServletRequest httpServletRequest = (HttpServletRequest) request;    String requestURI = httpServletRequest.getRequestURI();    StringBuffer requestURL = httpServletRequest.getRequestURL();    log.info("requestURI:" +requestURI+" "+"requestURL:"+requestURL);    chain.doFilter(httpServletRequest, response);  }}

通过 javaConfig方式配置 SpringBoot 过滤链类 FilterRegistrationBean,具体代码如下:

@Configurationpublic class FilterConfig {  @Bean  public FilterRegistrationBean filterRegistration() {    FilterRegistrationBean registration = new FilterRegistrationBean();    registration.setFilter(new UrlFilter());    List<String> urlList = new ArrayList<String>();    urlList.add("/*");    registration.setUrlPatterns(urlList);    registration.setName("UrlFilter");    registration.setOrder(1);    return registration;  }}

FilterRegistrationBean 中方法介绍:

registration.setFilter(Filter filter):设置我们自定义Filter对象。  registration.setUrlPatterns(Collection urlPatterns):设置自定义Filter需要拦截的URL的集合。  registration.setName(String name): 设置自定义Filter名称。  registration.setOrder(int order):设置自定义Filter拦截顺序。

测试

启动 SpirngBoot 项目并通过游览器访问我们的项目下的 index.html。

关于如何解析SpringBoot2快速整合Filter过程问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注主机评测网行业资讯频道了解更多相关知识。


上一篇:Python阶乘求和的代码怎么写

下一篇:如何使用建造者模式


SpringBoot
Copyright © 2002-2019 测速网 www.inhv.cn 皖ICP备2023010105号
测速城市 测速地区 测速街道 网速测试城市 网速测试地区 网速测试街道
温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!

热门搜索 城市网站建设 地区网站制作 街道网页设计 大写数字 热点城市 热点地区 热点街道 热点时间 房贷计算器