Spring Boot 定制URL匹配规则的方法
事情的起源:有人问我,说编写了一个/hello访问路径,但是吧,不管是输入/hello还是/hello.html,还是/hello.xxx都能进行访问。当时我还以为他对代码进行处理了,后来发现不是,后来发现这是SpringBoot路由规则。好了,有废话了下,那么看看我们解决上面这个导致的问题。
构建web应用程序时,并不是所有的URL请求都遵循默认的规则。有时,我们希望RESTfulURL匹配的时候包含定界符“.”,这种情况在Spring中可以称之为“定界符定义的格式”;有时,我们希望识别斜杠的存在。Spring提供了接口供开发人员按照需求定制。
核心的开发步骤就是两步:
(1)启动类extendsWebMvcConfigurationSupport
(2)重写configurePathMatch方法;
具体实现代码:
packagecom.kfit; importorg.springframework.boot.SpringApplication; importorg.springframework.boot.autoconfigure.SpringBootApplication; importorg.springframework.web.servlet.config.annotation.PathMatchConfigurer; importorg.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; /** * *@authorAngel--守护天使 *@versionv.0.1 *@date2016年7月29日下午7:06:11 */ @SpringBootApplication publicclassApiCoreAppextendsWebMvcConfigurationSupport{ /** *1、extendsWebMvcConfigurationSupport *2、重写下面方法; *setUseSuffixPatternMatch:设置是否是后缀模式匹配,如“/user”是否匹配/user.*,默认真即匹配; *setUseTrailingSlashMatch:设置是否自动后缀路径模式匹配,如“/user”是否匹配“/user/”,默认真即匹配; */ @Override publicvoidconfigurePathMatch(PathMatchConfigurerconfigurer){ configurer.setUseSuffixPatternMatch(false) .setUseTrailingSlashMatch(true); } publicstaticvoidmain(String[]args){ SpringApplication.run(ApiCoreApp.class,args); } }
其中访问代码:
@RequestMapping("/user") publicStringhello(){ return"/user"; }
以上代码有两句核心的代码:
setUseSuffixPatternMatch(booleanuseSuffixPatternMatch):
设置是否是后缀模式匹配,如“/user”是否匹配/user.*,默认真即匹配;
当此参数设置为true的时候,那么/user.html,/user.aa,/user.*都能是正常访问的。
当此参数设置为false的时候,那么只能访问/user或者/user/(这个前提是setUseTrailingSlashMatch设置为true了)。
setUseTrailingSlashMatch(booleanuseSuffixPatternMatch):
设置是否自动后缀路径模式匹配,如“/user”是否匹配“/user/”,默认真即匹配;
当此参数设置为true的会后,那么地址/user,/user/都能正常访问。
当此参数设置为false的时候,那么就只能访问/user了。
当以上两个参数都设置为true的时候,那么路径/user或者/user.aa,/user.*,/user/都是能正常访问的,但是类似/user.html/是无法访问的。
当都设置为false的时候,那么就只能访问/user路径了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。