通过 thymeleaf 片段共享数据 [英] Share data via thymeleaf fragment

查看:38
本文介绍了通过 thymeleaf 片段共享数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 nav 的 thymeleaf 片段,我将其包含在所有前端页面中,如下所示:

</nav>

但我现在想要做的是从数据库中获取一些数据,并在此片段中提供这些数据,然后这些数据将出现在包含此片段的每个页面上.

如果我想定期从控制器向视图传递数据,我将使用 Modelmodel.addAttribute 并返回包含相关模型的适当视图数据,但如何将数据传递给这个片段?

解决方案

  1. 您可以创建一个拦截器并在 postHandle 方法上添加模型属性(它允许您访问 ModelAndView 对象.拦截器必须在具有此片段的所有控制器.

  2. 您可以将相关的模型属性添加到会话中,并通过 ${session.attribute} 访问它们.

  3. 结合使用 @ControllerAdvice 注释和 @ModelAttribute 为所有控制器添加模型属性.

I have a thymeleaf fragment called nav which I include in all front-end pages, it goes like so:

<nav class="navbar navbar-expand-md navbar-dark bg-dark" th:fragment="nav">
    <div class="collapse navbar-collapse" id="navbarsExampleDefault">
        <ul class="navbar-nav mr-auto">
            <li class="nav-item active">
                <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
            </li>
How to get Java data here ?
        </ul>
    </div>
</nav>

But what I want to do now is get some data from the database and have that data available in this fragment, which in turn will appear on every page that includes this fragment.

If I want to pass data to a view regularly from a controller, I would use Model and model.addAttribute and return the appropriate view which would contain the relevant model data, but how can I pass data to this fragment?

解决方案

  1. You can create an interceptor and add model attribute on the postHandle method (which allows you access to the ModelAndView object. The interceptor will have to be on all the controllers that have this fragment.

  2. You can add the relevant model attributes to the session and access them via ${session.attribute}.

  3. Use the @ControllerAdvice annotation in combination with @ModelAttribute to add a model attribute to all controllers.

这篇关于通过 thymeleaf 片段共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆