7

I have a number of controller methods spread over a number of classes. Every method takes a Model object and all of my methods populate some shared properties into the model (control the navigation bar display mostly). Is there a way for me to plug a 'base' method into Spring? I want one method that can populate my shared properties and then go into the specific controller method (or reversed for that matter). Does anybody know how to do that?

3 Answers 3

3

Sounds like a HandlerInterceptor might be a good approach.

It's a bit AOP like -- you can define a class that has a PreHandle or PostHandle method, and configure which requests it will run on. In your case you probably want a PostHandle, since that will give you access to the ModelAndView, so you can populate it with the shared items.

Sign up to request clarification or add additional context in comments.

Comments

2

There are several extension points in Spring and Spring MVC you can take:

  • HandlerInterceptor - a simple way to intercept each handler method
  • Spring AOP - before/after advice matching all your controllers
  • WebArgumentResolver - maybe you can somehow customize resolving arguments and process them before calling the controller?

Comments

1

If the logic you're implementing is a cross cutting concern that's not generally coupled to particular views, I would suggest using an interceptor rather than creating controller functional-hierarchies. Controller hierarchies can make it hard to deal when it comes to things like exception mapping and session data management/lifecycle. Plus, the view tier is where you're most likely to need to change things over time for changing customer demands, so a future proof functional-hierarchy isn't going to happen.

org.springframework.web.servlet.HandlerInterceptor has a 'postHandle' method that gives you access to the request, controller that handled the request, and the ModelMap. That should be all you need. If you need some control from the controller, you can always add meta-data to it indicating, for example, which class of header it uses (then in the future when you have to change that, it's one string in an xml or annotation, instead of changing what class you inherit from and all that entails.)

You turn them on like this:

<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
    <property name="interceptors">
        <list>
            <bean class="a.package.MyHandlerInterceptor"/>
        </list>
    </property>
</bean>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.