How to make Model attribute global?

I am using Spring MVC Framework and I would like all .jsp pages in the view to have access to user attributes (name, gender, age ...). So far, I have used the addAttribute Model(UI) method in each controller to pass the current user attributes to the View . Is there a way to do this only once and avoid the same code in each Controller ?

+10
java spring model-view-controller
source share
2 answers

You can use the Spring @ControllerAdvice annotation for the new controller class as follows:

 @ControllerAdvice public class GlobalControllerAdvice { @ModelAttribute("user") public List<Exercice> populateUser() { User user = /* Get your user from service or security context or elsewhere */; return user; } } 

The "populateUser" method will be executed for each request, and since it has the @ModelAttribute annotation, the result of the method (user) will be placed in the model for each request.

The user will be available in your jsp using $ {user}, as this name was assigned by @ModelAttribute (example: @ModelAttribute ("fooBar") → $ {fooBar})

You can pass some arguments to the @ControllerAdvice annotation to indicate which controllers are recommended by this global controller. For example:

 @ControllerAdvice(assignableTypes=FooController.class,BarController.class}) or @ControllerAdvice(basePackages="foo.bar.web.admin","foo.bar.web.management"})) 
+21
source share

When it comes to user attributes, you can bind the bean to a session as an attribute that can be accessed on every view. This needs to be done only once.

Another option would be to implement a HandlerInterceptor and expose the model for each request.

0
source share

All Articles