如何使Model属性成为全局属性? [英] How to make a Model attribute global?

查看:62
本文介绍了如何使Model属性成为全局属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring MVC Framework,并且希望视图的所有.jsp页都可以访问用户的属性(姓名,性别,年龄...).到目前为止,我在每个Controller中使用Model(UI)addAttribute方法将当前用户的属性传递给View.有没有办法只执行一次,并避免在每个Controller中都使用相同的代码?

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?

推荐答案

您可以在新的Controller类上使用Spring的@ControllerAdvice批注,如下所示:

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;
    }
}

"populateUser"方法将在每个请求上执行,并且由于具有@ModelAttribute批注,因此该方法(用户)的结果将被放入每个请求的模型中.

The "populateUser" method will be executed on every request and since it has a @ModelAttribute annotation, the result of the method (the user) will be put into the model for every request.

将使用$ {user}在jsp中使用该用户,因为该名称是@ModelAttribute的名称(例如:@ModelAttribute("fooBar")-> $ {fooBar})

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

您可以将一些参数传递给@ControllerAdvice批注,以指定此Global控制器建议使用哪些控制器.例如:

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"}))

这篇关于如何使Model属性成为全局属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆