如何使用Thymeleaf和Spring Boot创建动态链接?

Ben*_*t D 2 spring thymeleaf spring-boot

所以我一直在用Thymeleaf和Spring Boot在我的电脑上托管一个"网站",我有一个基本的,不安全的登录,我为了好玩.我目前要做的是创建一个链接,将您带回到基于上一页的上一页,该链接通过模型以字符串形式发送.

以下是几个片段:在控制器中:

@RequestMapping("/")
public String index(Model model) {
    return ifLoggedIn(model, "home", "");
}

private String ifLoggedIn (Model model, String location, String returnTo) {
    if (Login.loggedIn.getOrDefault(Login.IP(), Boolean.FALSE)) {
        return location;
    } else {
        model.addAttribute("login", new Login());
        model.addAttribute("return_page", returnTo);
        return "login";
    }
}
Run Code Online (Sandbox Code Playgroud)

在loggedin.html文件中(成功登录后):

<body>
    <a th:href="'/' + ${return_page}">Return to previous location</a>
</body>
Run Code Online (Sandbox Code Playgroud)

编辑:

我首先更改loggedin.html文件中的行以遵循Pau建议的内容:

<a th:href="@{'/' + ${return}}">Return to previous location</a>
Run Code Online (Sandbox Code Playgroud)

但是我一直被重定向到server.local/null,所以我尝试删除了'/' +ifLoggedIn参数中的/,所以它会是return ifLoggedIn(model, "home", "/",但是这也一直把我发送到server.local/null.现在,我只是将loggedin.html文件中的行更改为以下内容:

<a th:if="(${return_page} != null)" th:with="return=(${return_page})" th:href="@{${return}}">Return to previous location</a> 
Run Code Online (Sandbox Code Playgroud)

现在它就消失了,这意味着$ {return_page}等于null.回头看一下控制器,我不明白为什么它会返回null.另一件事,我正在重定向回到其他页面,有一行说return ifLoggedIn(model, "messages", "/messages",但即使有那些我仍然被发送到server.local/null.

Pau*_*Pau 6

您需要使用链接表达式,使用@{...}哪种类型Thymeleaf Standard Epression.在官方文档中,您可以在部分中的链接表达式中看到许多使用表达式的示例9. Using expressions in URLs:

没问题!每个URL参数值实际上都是一个表达式,因此您可以轻松地将您的文字替换为任何其他表达式,包括i18n,conditionals ...:

....

URL基本身可以指定为表达式,例如变量表达式:

<a th:href="@{${detailsURL}(id=${order.id})}">

此外,在本教程中,有一个与您类似的表达式,在4.4链接URL中:

URL基数也可以是评估另一个表达式的结果:

...

<a th:href="@{'/details/'+${user.login}(orderId=${o.id})}">view</a>


所以在你的情况下,它会像下一个:

<body>
    <a th:href="@{'/' + ${return_page}}">Return to previous location</a>
</body>
Run Code Online (Sandbox Code Playgroud)


小智 5

你可以使用这个:

控制器

@GetMapping("/userLogin/{userId}")
public String getUserDetailsById(@PathVariable("userId") int userId, Model model){
    return "user/userDetails";
 }
Run Code Online (Sandbox Code Playgroud)

HTML

<body>
   <a th:href="@{/userLogin/{userId}(userId=${user.userId})}"></a> 
</body>
Run Code Online (Sandbox Code Playgroud)