Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to execute repetitive Spring controller code?

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?

like image 445
Claude Avatar asked May 18 '11 17:05

Claude


1 Answers

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.

like image 130
Bozho Avatar answered Oct 01 '22 22:10

Bozho