spring boot @PathVariable 避免最后点号.之后的内容被截断

Java 2020-03-07 阅读 130 评论 0

问题描述

使用spring boot,定义一个搜索的请求,如下。

@RequestMapping(path = "/{keywords}", method = RequestMethod.GET)
public String index(@PathVariable("keywords") String keywords) {
    logger.info(keywords);
    return "result";
}

使用以下 url 访问,打印输出结果:

url 输入/google,keywords 显示google

url 输入/google.com,keywords 显示google

url输入/cloud.google.com,keywords 显示cloud.google

可以看到带点号"."的路径,最后一个点号"."后面的参数内容丢失了。以下介绍2种解决方法。

解决方法1

将注解 @RequestMapping 的 path 设置为 {keywords:.+},匹配点号".",避免点号被截取。

@RequestMapping(path = "/{keywords:.+}", method = RequestMethod.GET)
public String index(@PathVariable("keywords") String keywords) {
    logger.info(keywords);
    return "result";
}

解决方法2

配置 extends WebMvcConfigurerAdapter 类,重写configurePathMatch方法,设置 setUseSuffixPatternMatch为 false。

@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
    configurer.setUseSuffixPatternMatch(false);
}

查看setUseSuffixPatternMatch的源代码如下。默认情况下为true,/users.php等价于/users,导致了接收到的路径参数被删除,设置为false即可。

/**
 * Whether to use suffix pattern match (".*") when matching patterns to
 * requests. If enabled a method mapped to "/users" also matches to "/users.*".
 * <p>By default this is set to {@code true}.
 * @see #registeredSuffixPatternMatch
 */
public PathMatchConfigurer setUseSuffixPatternMatch(Boolean suffixPatternMatch) {
    this.suffixPatternMatch = suffixPatternMatch;
    return this;
}
最后更新 2020-03-07
MIP.watch('startSearch', function (newVal, oldVal) { if(newVal) { var keyword = MIP.getData('keyword'); console.log(keyword); // 替换当前历史记录,新增 MIP.viewer.open('/s/' + keyword, {replace: true}); setTimeout(function () { MIP.setData({startSearch: false}) }, 1000); } }); MIP.watch('goHome', function (newVal, oldVal) { MIP.viewer.open('/', {replace: false}); });