【问题标题】:How to add an element id to the url of the Thymeleaf template in the controller in Spring如何在 Spring 的控制器中将元素 id 添加到 Thymeleaf 模板的 url
【发布时间】: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>

【问题讨论】:

    标签: spring thymeleaf


    【解决方案1】:

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

    src/main/resources/templates/index.html

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

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

    Controller.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";
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用?id=value 在 URL 中添加 id。

      在控制器@RequestMapping("/path/{id}") 访问该变量@PathVariable

      【讨论】:

        猜你喜欢
        • 2015-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-14
        • 1970-01-01
        相关资源
        最近更新 更多