Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot Menu Component Controller

I'm wondering how I can create a menu that is loaded dynamically (from the db) on every page.

I use spring boot + thymeleaf. no XML, just spring annotations.

I tried adding a controller with a method that returns a category object (which is used in the menu) annotated with (@ModelAttribute) but I couldn't use that attribute in my HTML pages. Here is my header:

<ul>
<li th:each="category : ${categories}" th:text="${category.name}">
</ul>

Now, this "ul" is loaded in every page since it's on the menu bar. I don't want to add the following code in every controller:

ModelAndView mav = new ModelAndView("index");
mav.addObject("categories", getCategories());

I need a way to achieve this without adding this code on every controller. just once.

Thanks

like image 485
Ja'afar Naddaf Avatar asked Oct 23 '25 18:10

Ja'afar Naddaf


1 Answers

You can use @ControllerAdvice, adding "categories" attribute for each controller response. Since it's a spring component, you can autowire any of your existing services in it to retrieve categories.

@ControllerAdvice
public class CategoriesAdvice {

    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("categories", getCategories());
    }
}

See my github project with complete solution: project

like image 117
Ilya Zinkovich Avatar answered Oct 26 '25 08:10

Ilya Zinkovich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!