Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a Model attribute global?

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?

like image 394
tony Avatar asked Nov 23 '15 17:11

tony


People also ask

What is difference between @RequestBody and @ModelAttribute?

@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.

How do you add attributes to a model?

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.

What is a model attribute?

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.

Can we map a request with model attribute?

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.


1 Answers

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"}))
like image 190
wesker317 Avatar answered Sep 19 '22 14:09

wesker317