Spring Security 实战干货:路径Uri中的 Ant 风格

1. 前言

咱们常常在读到一些文章会遇到uri 支持 Ant 风格 ,并且这个东西在 Spring MVCSpring Security 中常常被说起。这究竟是什么呢?今天咱们来学习了解一下。这对咱们学习 Spring MVCSpring Security 十分必要。html

2. Ant 风格

说白了 Ant 风格就是一种路径匹配表达式。主要用来对uri的匹配。其实跟正则表达式做用是同样的,只不过正则表达式适用面更加宽泛,Ant仅仅用于路径匹配。java

3. Ant 通配符

Ant 中的通配符有三种:正则表达式

  • ? 匹配任何单字符
  • * 匹配0或者任意数量的 字符
  • ** 匹配0或者更多的 目录

这里注意了单个* 是在一个目录内进行匹配。 而** 是能够匹配多个目录,必定不要迷糊。app

3.1 Ant 通配符示例

通配符 示例 说明
? /ant/p?ttern 匹配项目根路径下 /ant/pattern/ant/pXttern,可是不包括/ant/pttern
* /ant/*.html 匹配项目根路径下全部在ant路径下的.html文件
* /ant/*/path /ant/path/ant/a/path/ant/bxx/path 都匹配,不匹配 /ant/axx/bxx/path
** /ant/**/path /ant/path/ant/a/path/ant/bxx/path/ant/axx/bxx/path都匹配

3.2 最长匹配原则

从 3.1 能够看出 *** 是有冲突的状况存在的。为了解决这种冲突就规定了最长匹配原则(has more characters)。 一旦一个uri 同时符合两个Ant匹配那么走匹配规则字符最多的。为何走最长?由于字符越长信息越多就越具体。好比 /ant/a/path 同时知足 /**/path/ant/*/path 那么走/ant/*/pathide

4. Spring MVC 和 Spring Security 中的 Ant 风格

接下来咱们来看看 Spring MVCSpring Security 下的 Ant风格。学习

4.1 Spring MVC 中的 Ant 风格

这里也提一下在 Spring MVC 中 咱们在控制器中写以下接口:ui

/**
      * ant style test.
      *
      * @return the string
      */
     @GetMapping("/?ant")
     public String ant() {
 
         return "ant";
     }

你使用任意合法uri字符替代? 发现均可以匹配,好比/bant 。 还有Spring MVC 的一些 过滤器注册、格式化器注册都用到了 Ant 风格。code

4.2 Spring Security 中的 Ant 风格

Spring SecurityWebSecurityConfigurerAdapter 中的你能够经过以下配置进行路由权限访问控制:htm

public class SecurityConfig extends WebSecurityConfigurerAdapter {
  
      @Autowired
      public void configureGlobal(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
          authenticationManagerBuilder.inMemoryAuthentication().withUser("admin").password("admin").roles("USER");
      }
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http.authorizeRequests()
                  //放行静态资源 首页
                  .antMatchers("/index.html","/static/**").permitAll()
                  .anyRequest().authenticated();
      }
  }

上面 Spring Security 的配置中在 antMatchers 方法中经过 Ant 通配符来控制了资源的访问权限。 后面我也会出相关的教程,敬请关注公众号:Felordcn 和我的博客:https://felord.cnblog

5. 总结

Ant 风格总体东西很少,也很好理解。 不少关于uri 的配置、路由匹配、处理都用到了 Ant 风格 。对于 Web 开发人员来讲是必须掌握的技能之一。

关注公众号:Felordcn获取更多资讯

我的博客:https://felord.cn

相关文章
相关标签/搜索