Reputation: 73
I have a library method Common.addTheUsualStuffToTheModel(model)
that needs to add various attributes to the model in every controller method in my app.
@RequestMapping(value = "/everypath", method = RequestMethod.GET)
public final String everyHandler(ModelMap model)
{
model = Common.addTheUsualStuffToTheModel(model);
return "everyPage";
}
So far I have been adding this same line to every handler method:
model = Common.addTheUsualStuffToTheModel(model);
But I'm afraid this is not consistent with the principle of "write once, use everywhere".
How do I avoid repeating this code in every handler?
Upvotes: 5
Views: 1990
Reputation: 597432
You can use an interceptor and <mvc:interceptors>
to do that
In your interceptor you can add anything as request attribute (which is in fact where the model attributes go). The interceptor code is executed before or after each method (that matches the interceptor mapping).
If you don't necessarily need the model to be populated before the controller method, in the postHandle
method you get the ModelAndView
object.
Upvotes: 7
Reputation: 26584
What about specifying @ModelAttribute annotated reference data provider methods. If you had a base class for all of your controllers, and that base class had @ModelAttribute annotated methods then I believe that data would be available in the model for all views handled by those controllers. Have a look at 15.3.2.8 in the Spring docs.
Upvotes: 0