点击上方蓝色“ 程序猿DD ”,选择“设为星标”
回复“ 资源 ”获取独家整理的学习资料!
来源 | juejin.im/post/5c6b6b126fb9a04a0c2f024f
1 . 前言
我们经常在读到一些文章会遇到 uri 支持 Ant 风格 ,而且这个东西在 Spring MVC 和 Spring Security 中经常被提及。 这到底是什么呢? 今天我们来学习了解一 下。 这对我们学习 Spring MVC 和 Spring Security 十分必要。
说白了 Ant 风格就是一种路径匹配表达式。 主要用来对 uri 的匹配。 其实跟正则表达 式作用是一样的,只不过正则表达式适用面更加宽泛, Ant 仅仅用于路径匹配。
Ant 中的通配符有三种:
? 匹配任何单字符
* 匹配0或者任意数量的 字符
** 匹配0或者更多的 目录
这里注意了单个 * 是在一个目录内进行匹配。 而 ** 是可以匹配多个目录,一定不要迷糊。
从 3.1 可以看出 * 和 ** 是有冲突的情况存在的。 为了解决这种冲突就规定了最长匹配原则(has more characters)。 一旦一个 uri 同时符合两个 Ant 匹配那么走匹配规则字符最多的。 为什么走最长? 因为字符越长信息越多就越具体。 比如 /ant/a/path 同时满足 /**/path 和 /ant/*/path 那么走 /ant/*/path
接下来我们来看看 Spring MVC 和 Spring Security 下的 Ant 风格。
这里也提一下在 Spring MVC 中 我们在控制器中写如下接口:
/**
* ant style test.
*
* @return the string
*/
@GetMapping("/?ant")
public String ant() {
return "ant";
}
你使用任意合法 uri 字符替代 ? 发现都可以匹配,比如 /bant 。 还有Spring MVC 的一些 过滤器注册、格式化器注册都用到了 Ant 风格。
在 Spring Security 中 WebSecurityConfigurerAdapter 中的你可以通过如下配置进行路由权限访问控制:
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.cn
Ant 风格整体东西不多,也很好理解。很多关于 uri 的配置、路由匹配、处理都用到了 Ant 风格 。对于 Web 开发人员来说是必须掌握的技能之一 。
本文通过OpenWrite的Markdown转换工具发布
关注我,回复“ 加群 ” 加入各种主题讨论群
RESTful 架构基础
17 个方面,综合对比四大消息中间件
9 个爱不释手的 JSON 工具
手把手教你定制标准 Spring Boot starter
程序员接私活的10个平台和一些建议
朕已阅