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?
@ModelAttribute is used for binding data from request param (in key value pairs), but @RequestBody is used for binding data from whole body of the request like POST,PUT.. request types which contains other format like json, xml.
To add new custom attributes to an entity, from the Edit Business Entity page, expand the Data Model section by clicking on it, then click the Insert button. The Add Attribute page appears where you will provide the properties.
Model attributes are the data representations used internally by the model. Data attributes and model attributes can be the same. For example, a column called SIZE , with values S , M , and L , are attributes used by an algorithm to build a model.
Method level ModelAttribute annotation cannot be mapped directly with any request. Let's take a look at the following example for better understanding. We have 2 different methods in the above example.
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"}))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With