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
?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
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.
You can use Spring's @ControllerAdvice annotation on a new Controller class like this:
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.
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: