关于Spring中的useSuffixPatternMatch
背景
spring-boot的版本是2.1.4.RELEASE,spring的版本是5.1.6.RELEASE
一个例子如下:
@Configuration
@Import(WebMvcAutoConfiguration.EnableWebMvcConfiguration.class)
@SuppressWarnings("unchecked")
public class WebConfig implements WebMvcConfigurer, WebMvcRegistrations {
@Override
public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
return new RequestMappingHandlerMapping();
}
}
@RestController
public class ParamController {
@GetMapping(value = "/param/{param1}")
public String param(@PathVariable("param1") String param1) {
return param1;
}
}
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
启动一下,访问http://127.0.0.1:8080/param/hehe和http://127.0.0.1:8080/param/hehe.hehe都返回hehe
如果访问http://127.0.0.1:8080/param/hehe.hehe.hehe,它会返回hehe.hehe
所以会发现它把最后一个小数点后面的字符给截掉了,那如果我们想要获取完整的字符串,该怎么办呢?
探索
- 参数怎么来的
入口在InvocableHandlerMethod.invokeForRequest,如下:

是根据PathVariableMethodArgumentResolver.resolveName得来的,如下:

HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE = HandlerMapping.class.getName() + ".uriTemplateVariables";
什么时候放进attributes里的?,在RequestMappingInfoHandlerMapping.handleMatch,如下:

- 参数怎么解析的
程序定义的:/param/{param1} -> /param/{param1}.*
接口传过来的:/param/hehe.hehe
以/分割,第一个字符串param里没有参数,所以会跳过,直接看第二个字符串:
{param1}.* -> pattern=(.*)\Q.\E.*
hehe.hehe
param1=hehe
我们定义的是/param/{param1},怎么就变成了/param/{param1}.*?在PatternsRequestCondition.getMatchingPattern

可以看到如果useSuffixPatternMatch为true,并且指定的url里没有.,会在后缀自动增加.*
- useSuffixPatternMatch是在哪里设置的?
public class RequestMappingHandlerMapping extends RequestMappingInfoHandlerMapping
implements MatchableHandlerMapping, EmbeddedValueResolverAware {
private boolean useSuffixPatternMatch = true;
@Override
public void afterPropertiesSet() {
this.config = new RequestMappingInfo.BuilderConfiguration();
this.config.setUrlPathHelper(getUrlPathHelper());
this.config.setPathMatcher(getPathMatcher());
this.config.setSuffixPatternMatch(this.useSuffixPatternMatch); // 这里设置了
this.config.setTrailingSlashMatch(this.useTrailingSlashMatch);
this.config.setRegisteredSuffixPatternMatch(this.useRegisteredSuffixPatternMatch);
this.config.setContentNegotiationManager(getContentNegotiationManager());
super.afterPropertiesSet();
}
}
解决
- 修改
WebConfig的getRequestMappingHandlerMapping
@Configuration
@Import(WebMvcAutoConfiguration.EnableWebMvcConfiguration.class)
@SuppressWarnings("unchecked")
public class WebConfig implements WebMvcConfigurer, WebMvcRegistrations {
@Override
public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
RequestMappingHandlerMapping requestMappingHandlerMapping = new RequestMappingHandlerMapping();
requestMappingHandlerMapping.setUseSuffixPatternMatch(false);
return requestMappingHandlerMapping;
}
}
- 增加
configurePathMatch方法
@Configuration
@Import(WebMvcAutoConfiguration.EnableWebMvcConfiguration.class)
@SuppressWarnings("unchecked")
public class WebConfig implements WebMvcConfigurer, WebMvcRegistrations {
@Override
public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
return new RequestMappingHandlerMapping();
}
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.setUseSuffixPatternMatch(false);
}
}
- url中增加点
a. 中间的参数是不受影响的
@RestController
public class ParamController {
@GetMapping(value = "/param/{param1}/{param2}")
public String param(@PathVariable("param1") String param1, @PathVariable("param2") String param2) {
return param1 + " " + param2;
}
}
访问http://127.0.0.1:8080/param/hehe.hehe/hehe.hee返回hehe.hehe hehe
b. 增加点
@RestController
public class ParamController {
//@GetMapping(value = "/param/{param1}")
//public String param(@PathVariable("param1") String param1) {
// return param1;
//}
@GetMapping(value = "/param/{param1}.{param2}")
public String param(@PathVariable("param1") String param1, @PathVariable("param2") String param2) {
return param1 + " " + param2;
}
}
访问http://127.0.0.1:8080/param/hehe.hehe返回hehe hehe
注意第一个方法和第二个方法不要同时出现,如果同时出现的话,则会访问第一个方法
@RestController
public class ParamController {
@GetMapping(value = "/param/{param1}")
public String param(@PathVariable("param1") String param1) {
return param1;
}
@GetMapping(value = "/param/{param1}.{param2}")
public String param(@PathVariable("param1") String param1, @PathVariable("param2") String param2) {
return param1 + " " + param2;
}
}
访问http://127.0.0.1:8080/param/hehe.heh返回hehe
- 修改参数
@RestController
public class ParamController {
@GetMapping(value = "/param/{param1:.+}")
public String param(@PathVariable("param1") String param1) {
return param1;
}
}
访问http://127.0.0.1:8080/param/hehe.hehe,返回hehe.hehe
原因如下:
/param/{param1:.+} -> /param/{param1:.+}
/param/hehe.hehe
{param1:.+} -> pattern=(.+)
hehe.hehe
param1=hehe.hehe
得到pattern以及提取参数的类 AntPathStringMatcher
protected static class AntPathStringMatcher {
private static final Pattern GLOB_PATTERN = Pattern.compile("\\?|\\*|\\{((?:\\{[^/]+?\\}|[^/{}]|\\\\[{}])+?)\\}");
private static final String DEFAULT_VARIABLE_PATTERN = "(.*)";
private final Pattern pattern;
private final List<String> variableNames = new LinkedList<>();
public AntPathStringMatcher(String pattern) {
this(pattern, true);
}
public AntPathStringMatcher(String pattern, boolean caseSensitive) {
StringBuilder patternBuilder = new StringBuilder();
Matcher matcher = GLOB_PATTERN.matcher(pattern);
int end = 0;
while (matcher.find()) {
patternBuilder.append(quote(pattern, end, matcher.start()));
String match = matcher.group();
if ("?".equals(match)) {
patternBuilder.append('.');
}
else if ("*".equals(match)) {
patternBuilder.append(".*");
}
else if (match.startsWith("{") && match.endsWith("}")) {
int colonIdx = match.indexOf(':');
if (colonIdx == -1) {
patternBuilder.append(DEFAULT_VARIABLE_PATTERN);
this.variableNames.add(matcher.group(1));
}
else {
String variablePattern = match.substring(colonIdx + 1, match.length() - 1);
patternBuilder.append('(');
patternBuilder.append(variablePattern);
patternBuilder.append(')');
String variableName = match.substring(1, colonIdx);
this.variableNames.add(variableName);
}
}
end = matcher.end();
}
patternBuilder.append(quote(pattern, end, pattern.length()));
this.pattern = (caseSensitive ? Pattern.compile(patternBuilder.toString()) :
Pattern.compile(patternBuilder.toString(), Pattern.CASE_INSENSITIVE));
}
private String quote(String s, int start, int end) {
if (start == end) {
return "";
}
return Pattern.quote(s.substring(start, end));
}
/**
* Main entry point.
* @return {@code true} if the string matches against the pattern, or {@code false} otherwise.
*/
public boolean matchStrings(String str, @Nullable Map<String, String> uriTemplateVariables) {
Matcher matcher = this.pattern.matcher(str);
if (matcher.matches()) {
if (uriTemplateVariables != null) {
// SPR-8455
if (this.variableNames.size() != matcher.groupCount()) {
throw new IllegalArgumentException("The number of capturing groups in the pattern segment " +
this.pattern + " does not match the number of URI template variables it defines, " +
"which can occur if capturing groups are used in a URI template regex. " +
"Use non-capturing groups instead.");
}
for (int i = 1; i <= matcher.groupCount(); i++) {
String name = this.variableNames.get(i - 1);
String value = matcher.group(i);
uriTemplateVariables.put(name, value);
}
}
return true;
}
else {
return false;
}
}
}
关于Spring中的useSuffixPatternMatch的更多相关文章
- Velocity初探小结--Velocity在spring中的配置和使用
最近正在做的项目前端使用了Velocity进行View层的数据渲染,之前没有接触过,草草过了一遍,就上手开始写,现在又回头细致的看了一遍,做个笔记. velocity是一种基于java的模板引擎技术, ...
- Spring中Bean的作用域、生命周期
Bean的作用域.生命周期 Bean的作用域 Spring 3中为Bean定义了5中作用域,分别为singleton(单例).protot ...
- Spring中Bean的实例化
Spring中Bean的实例化 在介绍Bean的三种实例化的方式之前,我们首先需要介绍一下什么是Bean,以及Bean的配置方式. 如果 ...
- 模拟实现Spring中的注解装配
本文原创,地址为http://www.cnblogs.com/fengzheng/p/5037359.html 在Spring中,XML文件中的bean配置是实现Spring IOC的核心配置文件,在 ...
- Spring中常见的bean创建异常
Spring中常见的bean创建异常 1. 概述 本次我们将讨论在spring中BeanFactory创建bean实例时经常遇到的异常 org.springframework.beans.fa ...
- Spring中配置数据源的4种形式
不管采用何种持久化技术,都需要定义数据源.Spring中提供了4种不同形式的数据源配置方式: spring自带的数据源(DriverManagerDataSource),DBCP数据源,C3P0数据源 ...
- spring中InitializingBean接口使用理解
InitializingBean接口为bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是继承该接口的类,在初始化bean的时候会执行该方法. 测试程序如下: imp ...
- Quartz 在 Spring 中如何动态配置时间--转
原文地址:http://www.iteye.com/topic/399980 在项目中有一个需求,需要灵活配置调度任务时间,并能自由启动或停止调度. 有关调度的实现我就第一就想到了Quartz这个开源 ...
- Spring中的cglib动态代理
Spring中的cglib动态代理 cglib:Code Generation library, 基于ASM(java字节码操作码)的高性能代码生成包 被许多AOP框架使用 区别于JDK动态代理,cg ...
随机推荐
- 打败算法 —— 环形链表 II
本文参考 出自LeetCode上的题库 -- 环形链表II,哈希表和快慢指针两种解法都需要O(n)的时间,但快慢指针仅占用O(1)的空间 https://leetcode-cn.com/problem ...
- Effective Java —— 谨慎覆盖clone
本文参考 本篇文章参考自<Effective Java>第三版第十三条"Always override toString",在<阿里巴巴Java开发手册>中 ...
- 【动态规划】洛谷P1802 5 倍经验日(01背包问题)
一个洛谷普及-的题目,也是我刚刚入门学习动态规划的练习题. 下面发一下我的思路和代码题解: 我的思路及伪代码: 我的AC图: 接下来上代码: 1 //动态规划 洛谷P1802 五倍经验日 2 #inc ...
- hitcon_2017_ssrfme
hitcon_2017_ssrfme 进入环境给出源码 <?php if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $http_x_headers ...
- IOS动态调试汇总-傻瓜版教程
参考博客: https://juejin.cn/post/6872764160640450574#heading-4 (断点后续指令) https://www.jianshu.com/p/67f08a ...
- 单总线协议DS1820
一. DS18B20简介 DS18B20数字温度传感器接线方便,封装后可应用于多种场合,如管道式,螺纹式,磁铁吸附式,不锈钢封装式.主要根据应用场合的不同而改变其外观.封装后的DS18B20可用于电缆 ...
- JS+CSS实现数字滚动
最近在实现一个显示RGB颜色数值的动画效果时,尝试使用了writing-mode(书写模式)及 text-orientation来实现文字的竖直方向的排列,并借助CSS的transition(过渡)来 ...
- mpvue打包没有app.json等配置文件的解决方法
问题 一早上折腾了1个小时,小程序始终提示查找不到'app.json'文件.mpvue重新打包,光生成内容文件无配置文件. 解决办法 出错原因:版本问题 只需要把packpage.json里的mpvu ...
- Hive启动后show tables报错:Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient
错误详情: FAILED: HiveException java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive ...
- Python使用递归绘制谢尔宾斯基三角形
谢尔宾斯基三角形使用了三路递归算法,从一个大三角形开始,通过连接每一个边的中点,将大三角型分为四个三角形,然后忽略中间的三角形,依次对其余三个三角形执行上述操作. 运行效果: 源代码: 1 impor ...