如何使模型属性全局化? [英] How to make a Model attribute global?
问题描述
我正在使用 Spring MVC Framework
并且我希望 View 的所有 .jsp
页面都可以访问用户的属性(姓名、性别、年龄……).到目前为止,我在每个Controller中使用Model(UI)
的addAttribute
方法将当前User的属性传递给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
注释,该方法的结果(User
object) 将通过 user
名称为每个请求放入模型中,它在 @ModelAttribute
注释上声明.
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.
因此,使用 ${user}
的用户将在您的 jsp 中可用,因为这是给 @ModelAttribute
的名称(例如:@ModelAttribute("fooBar")
-> ${fooBar}
)
Theefore the user will be available in your jsp using ${user}
since that was the name given to the @ModelAttribute
(example: @ModelAttribute("fooBar")
-> ${fooBar}
)
您可以将一些参数传递给 @ControllerAdvice
注释,以指定此全局控制器建议哪些控制器.例如:
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})
或
@ControllerAdvice(basePackages={"foo.bar.web.admin","foo.bar.web.management"}))
这篇关于如何使模型属性全局化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!