Search⌘ K
AI Features

Global Model Attributes

Explore how to simplify your Spring Boot controllers by using @ModelAttribute for reusable model attributes and @ControllerAdvice for application-wide data injection. Understand how to maintain cleaner code by sharing attributes like user roles and application version across views with Thymeleaf templates.

We'll cover the following...

Controller specific

If we look at the various methods in UserController, we’ll see that some of the model attributes are added to the model in each method. Let’s look at a single method for reference:

Java
@GetMapping("/create")
@Secured("ROLE_ADMIN")
public String createUserForm(Model model) {
model.addAttribute("user", new CreateUserFormData());
model.addAttribute("genders", List.of(Gender.MALE, Gender.FEMALE, Gender.OTHER));
model.addAttribute("possibleRoles", List.of(UserRole.values()));
model.addAttribute("editMode", EditMode.CREATE);
return "users/edit";
}

The genders and possibleRoles attribute is also added in three other methods of the UserController. We could, of course, just create a method and ...