How to make a Model attribute global?

前端 未结 2 382
轮回少年
轮回少年 2021-01-04 06:32

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

2条回答
  •  一向
    一向 (楼主)
    2021-01-04 06:59

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

    @ControllerAdvice
    public class GlobalControllerAdvice {
    
        @ModelAttribute("user")
        public List 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"}))
    

提交回复
热议问题