16

I'm using Spring MVC Framework and I'd like all the .jsp pages of the View to have access to the User's attributes(name, sex, age...). So far, I use the addAttribute method of the Model(UI) in every Controller to pass the current User's attributes to the View. Is there a way to do this only once and avoid having the same code in every Controller?

RockAndRoll
  • 2,247
  • 2
  • 16
  • 35
nick
  • 1,611
  • 4
  • 20
  • 35
  • 1
    Take a look in this answer: http://stackoverflow.com/questions/7360784/add-attributes-to-the-model-of-all-controllers-in-spring-3 – deldev Nov 23 '15 at 17:17
  • If I do as it says then how would I access the Model attibute? – nick Nov 23 '15 at 17:34
  • then try this: http://stackoverflow.com/questions/15758877/how-to-display-model-attribute-in-jsp-using-spring-mvc – deldev Nov 23 '15 at 17:37

2 Answers2

34

You can use Spring's @ControllerAdvice annotation on a new Controller class like this:

@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 on every request and since it has a @ModelAttribute annotation, the result of the method (the User object) will be put into the model for every request through the user name, it declared on the @ModelAttribute annotation.

Theefore the user will be available in your jsp using ${user} since that was the name given to the @ModelAttribute (example: @ModelAttribute("fooBar") -> ${fooBar} )

You can pass some arguments to the @ControllerAdvice annotation to specify which controllers are advised by this Global controller. For example:

@ControllerAdvice(assignableTypes={FooController.class,BarController.class})

or

@ControllerAdvice(basePackages={"foo.bar.web.admin","foo.bar.web.management"}))
Manuel Jordan
  • 15,253
  • 21
  • 95
  • 158
wesker317
  • 2,172
  • 1
  • 16
  • 11
1

If it is about User's attributes, you can bind the model bean to session as an attribute which can be accessed on every view. This needs to be done only once.

Another option could be is to implement a HandlerInterceptor, and expose the model to every request.

Abhash Upadhyaya
  • 717
  • 14
  • 34