首页 > 解决方案 > 如何在 Spring 的控制器中将元素 id 添加到 Thymeleaf 模板的 url

问题描述

我有一个使用 Thymeleaf作为模板语言的 Spring 应用程序和服务器端渲染。一个按钮向Spring 中的控制器发送一个 get 或 post 请求,该控制器将一些消息发送到视图,该视图被呈现到 HTML 文件中并发送回客户端。该消息应该是可选的。这就是为什么模板也必须能够在没有消息的情况下被调用。

接下来,我希望客户端浏览器向下滚动到呈现此消息的页面部分,这通常很容易。您只需要将元素的 id 附加到 url,如下例所示。

https://stackoverflow.com/#footer

在此示例中,浏览器向下滚动到页面的页脚。

以下是我尝试过的。不幸的是,它不是那样工作的。Spring/Thymeleaf 试图找到一个找不到的 index#messagebox 模板。因此,会引发/显示 Whitelabel Error Page 错误。

页面.html

<section>
    <h2>Form to send request</h2>
    <form action="showmessage" method="get">
        <input type="submit" value="Click for message">
    </form>
</section>

控制器.java

@GetMapping("showmessage")
public ModelAndView showMessage(){
    return new ModelAndView("index#messagebox",Map.of("optionalmessage","Some message that is optioal"));
}

src/main/resources/templates/ index.html

<body>
    <h1>Index Page</h1>
    <div id="messagebox" th:fragment="message" th:with="optionalmessage=${optionalmessage}">
        <p th:if="${optionalmessage!=null}">[[${optionalmessage}]]</p>
    </div>
</body>

标签: springthymeleaf

解决方案


该问题可以通过 Flashmessages 和 Redirects 解决。html基本保持不变。如果设置了消息属性,则渲染它。

src/main/resources/templates/ index.html

<div th:if="${msg}">
    <div class="message" >
        <p>[[${msg}]]</p>
    </div>
</div>

必须在控制器中进行最重要的更改。首先,将 RedirectAttributes类型的参数添加到处理请求的控制器中。如果需要,可以使用RedirectAttributes.addFlashAttribute函数添加消息,如下所示。最后返回一个重定向,其中包含所需的标签。还需要第二个控制器来处理重定向的获取请求,并将模型作为输入参数并返回所需的模板。#tag只是通过传递给客户端浏览器。

控制器.java

@GetMapping("showMessage")
public String postNotification(RedirectAttributes redirectAttributes) {
    redirectAttributes.addFlashAttribute("optinalMessage", "Hello I am an optional message");
    return "redirect:/index#footer";
}
@GetMapping("index")
public String getIndex(Model model) {
    return "index";
}

推荐阅读