Thymeleaf中th:href如何自动忽略空查询参数(含路径变量场景)
Thymeleaf th:href链接参数动态显隐实现方法
问题场景
现有Thymeleaf链接定义代码如下:
th:href="@{/apps/role/{pathVar}(pathVar=${var.attribute}, search=${param.search})}"
当前代码可正常运行,但存在优化需求:当search查询参数为空时,URL中不显示该参数,保证链接格式整洁,预期效果如下:
- 当
param.search = 'test'时,生成的URL为"../apps/role/varAttr?search=test" - 当
param.search为空时,生成的URL为"../apps/role/varAttr"
之前尝试的预处理写法均无法生效,示例如下:
th:href="@{/apps/role/{pathVar}(pathVar=${var.attribute}, __(${param.search}=''?','search=${param.search})__)}"
th:href="@{/apps/role/{pathVar}(pathVar=${var.attribute}, __(${param.search}=''?,search=${param.search})__)}"
可行解决方案(适配Thymeleaf 3.0.11版本)
通过th:with先定义临时变量接收参数,再结合字符串判空和预处理逻辑实现,代码如下:
th:with="search=${param.search}" th:href="@{/apps/role/{pathVar}(pathVar=${var.attribute}, __(${#strings.isEmpty(search)} ? '' : ('search=' + ${search}))__)}"
核心逻辑:利用Thymeleaf预处理机制,运行时先判断
search参数是否为空,为空则输出空字符串,不为空则输出完整的参数键值对,避免空参数出现在最终生成的URL中。
内容的提问来源于stack exchange,提问作者jonas
相关产品推荐
相关产品推荐

