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