考虑以下控制器方法:
@RequestMapping(value = "/test", method = RequestMethod.GET)
public void test(@RequestParam(value = "fq", required = false) String[] filterQuery) {
logger.debug(fq = " + StringUtils.join(filterQuery, "|"));
}
Run Code Online (Sandbox Code Playgroud)
以下是不同fq组合的输出:
/test?fq=foo 结果是 fq = foo /test?fq=foo&fq=bar 结果是 fq = foo|bar /test?fq=foo,bar 结果是 fq = foo|bar /test?fq=foo,bar&fq=bash 结果是 fq = foo,bar|bash /test?fq=foo,bar&fq= 结果是 fq = foo,bar|例3是问题.我希望(想要/需要)它输出fq = foo,bar.
我已经尝试用逗号来逃避逗号\并使用其他%3C工作.
如果我看一下HttpServletRequest对象的版本:
String[] fqs = request.getParameterValues("fq");
logger.debug(fqs = " + StringUtils.join(fqs, "|"));
Run Code Online (Sandbox Code Playgroud)
它打印预期的输出:fqs = foo,bar …
我们有许多 @RestController 接收用户编写的通用语言短语。短语可以很长并且包含标点符号,例如句号,当然还有逗号。
简化控制器示例:
@RequestMapping(value = "/countphrases", method = RequestMethod.PUT)
public String countPhrases(
@RequestParam(value = "phrase", required = false) String[] phrase) {
return "" + phrase.length;
}
Run Code Online (Sandbox Code Playgroud)
Spring Boot 默认行为是以逗号分割参数值,因此之前的控制器使用以下 url 进行调用:
[...]/countphrases?phrase=john%20and%20me,%20you%and%her
将返回“2”而不是我们想要的“1”。事实上,使用逗号分割,前面的调用相当于:
[...]/countphrases?phrase=john%20and%20me&phrase=you%and%her
我们使用自然语言,我们需要准确分析用户如何编写短语并准确了解他们写了多少个短语。
我们尝试了这个解决方案:/sf/answers/2949438341/在将其适应我们的 Spring Boot 版本(2.0.5)后:
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
// we hoped this code could remove the "split strings at comma"
registry.removeConvertible(String.class, Collection.class);
}
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用。
有人知道如何在 Spring Boot 2.0.5 中全局删除“以逗号分隔字符串参数”行为吗?