【发布时间】:2021-01-13 17:08:49
【问题描述】:
我有一个 Spring 应用程序和 使用 Thymeleaf 进行服务器端渲染 作为模板语言。 一个按钮向 Spring 中的控制器发送 get 或 post 请求,它将一些消息发送到视图,该视图被呈现到 HTML 文件中并发送回客户端。该消息应该是可选的。这就是为什么模板也必须能够在没有消息的情况下被调用。
接下来我希望客户端浏览器向下滚动到页面中显示此消息的部分,这通常很容易。您只需要将元素的 id 附加到 url,如下例所示。
https://stackoverflow.com/#footer
在此示例中,浏览器向下滚动到页面的页脚。
以下是我尝试过的。不幸的是,它不是那样工作的。 Spring/Thymeleaf 试图找到一个找不到的 index#messagebox 模板。因此会引发/显示 Whitelabel Error Page 错误。
Page.html
<section>
<h2>Form to send request</h2>
<form action="showmessage" method="get">
<input type="submit" value="Click for message">
</form>
</section>
Controller.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>
【问题讨论】: