3

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?

jukenduit
  • 322
  • 3
  • 15

1 Answers1

1
  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.

Metroids
  • 18,999
  • 4
  • 41
  • 52
  • Can you give me some examples? Also - how can I set a session without any specific url/request being hit in the first place? Shoud I do it in some controller or the `WebConfig.java` file which would be ideal IMO. When I say example I mean something simple, `String name = "john"` where `name` is accessible throughout the application would suffice. – jukenduit Apr 18 '19 at 19:04
  • There are [lots](https://stackoverflow.com/a/42919020/4126893) [of](https://stackoverflow.com/a/8008402/4126893) [examples](https://stackoverflow.com/a/44373805/4126893). [Looks like you can also use `@ControllerAdvice` in combination with `@ModelAttribute` as well](https://stackoverflow.com/a/16979006/4126893). – Metroids Apr 18 '19 at 19:23
  • @ControllerAdvice seems to be working, I will accept this answer because on the hint – jukenduit Apr 18 '19 at 19:52