gpt4 book ai didi

java - 如何参数化 Spring Controller 和 thymeleaf 中的链接值?

转载 作者:行者123 更新时间:2023-11-30 01:41:03 25 4
gpt4 key购买 nike

我有两种映射“/cars/new”和“/used_cars”的方法:

@Controller
@RequestMapping("/cars")
public class CarsController {

@GetMapping("/new")
public String getNewCars() {
return "new_cars";
}
}

@Controller
@RequestMapping("/")
public class UsedCarsController {

@GetMapping("/used_cars")
public String getUsedCars() {
return "used_cars";
}
}

然后我在 html(thymeleaf) 中使用相同的链接值:

<nav>
<a th:href="@{/cars/new}">new cars</a> |
<a th:href="@{/used_cars}">used cars</a>
</nav>

如何在某些 *.properties 文件中参数化“/cars/new”和“/used_cars”的值以避免重复?

最佳答案

您可以使用属性来解决这个问题。在application.properties中定义属性

get.mapping.path=/new

然后在映射中使用该属性

@GetMapping("${get.mapping.path}")
public String getNewCars() {
return "new_cars";
}

Thymeleaf-docu可以向您解释如何从模板访问这些属性:

<nav>
<a th:href="${@environment.getProperty('get.mapping.path')}">new cars</a>
</nav>

如果您需要国际化支持,另一个 answer会帮助你的。

关于java - 如何参数化 Spring Controller 和 thymeleaf 中的链接值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59964506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com