java - Spring @RequestMapping "Not Contains"正则表达式

标签 java regex spring request-mapping

我有这个请求映射:

@RequestMapping(value = "/route/to-{destination}-from-{departure}.html", method = {RequestMethod.GET, RequestMethod.HEAD})

我想添加 RequestMapping:

@RequestMapping(value = "/route/to-{destination}.html", method = {RequestMethod.GET, RequestMethod.HEAD})

所以它可以服务所有“不出发”的航线。然而,这会产生冲突,因为“/route/to-destination-from-departure”url 实际上也与第二个 RequestMapping 匹配...... 很公平,所以我的解决方案是指定一个正则表达式:

@RequestMapping(value = "/route/to-{destination:^((?!-from-).)+}.html", method = {RequestMethod.GET, RequestMethod.HEAD})

这样,如果“destination”包含“-from-”,RequestMapping 将不匹配。

而且...它不起作用!第一个 RequestMapping 成功提供了 url“/route/to-barcelona-from-paris.html”,但根本没有提供 url“/route/to-barcelona.html”...我缺少什么?

注释:我不想使用java解决方案,例如有一个“/route/to-{destination}”RequestMapping,然后检查“destination”是否包含“-from-”..:)另外,我可以不要因为 SEO 而改变这些路线...

最佳答案

您可以使用

"/route/to-{destination:(?!.*-from-).+}.html"

^ anchor 将搜索字符串的开头,并且此处的任何匹配都会失败。

(?!.*-from-) 负向先行将使任何在除换行符之外的 0+ 个字符之后包含 -from- 的输入失败。

.+ 模式将消耗除换行符之外的所有 1 个或多个字符到行尾。

关于java - Spring @RequestMapping "Not Contains"正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52003857/

相关文章:

java - RichFaces中Ajax请求的取消

java - Boolean.TRUE 和 true 有什么区别

java - forEach 方法接受一个返回值的 lambda 表达式。为什么我没有遇到以下代码的编译问题?

java - 创建新的 Spring 注释

Spring Boot Maven 插件不创建可执行 jar

java - 加载用户在 JTable 中插入的所有单元格内容,并将它们作为对象存储在 LinkedList 中

JavaScript 正则表达式将字符串拆分为单词

c# - 在以另一个开头的字符串中查找所有命名组的出现

java - 我想检查一个字符串是否包含重复超过三次的特定字符

java - 如何使用jackson在java中将json转换为POJO