咱们常常在读到一些文章会遇到uri
支持 Ant
风格 ,并且这个东西在 Spring MVC 和 Spring Security 中常常被说起。这究竟是什么呢?今天咱们来学习了解一下。这对咱们学习 Spring MVC 和 Spring Security 十分必要。html
说白了 Ant
风格就是一种路径匹配表达式。主要用来对uri
的匹配。其实跟正则表达式做用是同样的,只不过正则表达式适用面更加宽泛,Ant
仅仅用于路径匹配。java
Ant
中的通配符有三种:正则表达式
?
匹配任何单字符*
匹配0或者任意数量的 字符**
匹配0或者更多的 目录这里注意了单个*
是在一个目录内进行匹配。 而**
是能够匹配多个目录,必定不要迷糊。app
通配符 | 示例 | 说明 |
---|---|---|
? |
/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.1 能够看出 *
和 **
是有冲突的状况存在的。为了解决这种冲突就规定了最长匹配原则(has more characters)。 一旦一个uri
同时符合两个Ant
匹配那么走匹配规则字符最多的。为何走最长?由于字符越长信息越多就越具体。好比 /ant/a/path
同时知足 /**/path
和 /ant/*/path
那么走/ant/*/path
ide
接下来咱们来看看 Spring MVC 和 Spring Security 下的 Ant
风格。学习
这里也提一下在 Spring MVC 中 咱们在控制器中写以下接口:ui
/** * ant style test. * * @return the string */ @GetMapping("/?ant") public String ant() { return "ant"; }
你使用任意合法uri
字符替代?
发现均可以匹配,好比/bant
。 还有Spring MVC 的一些 过滤器注册、格式化器注册都用到了 Ant
风格。code
在 Spring Security 中 WebSecurityConfigurerAdapter
中的你能够经过以下配置进行路由权限访问控制: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
Ant
风格总体东西很少,也很好理解。 不少关于uri
的配置、路由匹配、处理都用到了 Ant
风格 。对于 Web 开发人员来讲是必须掌握的技能之一。
关注公众号:Felordcn获取更多资讯