views:

185

answers:

2

I am new to Spring MVC 3 and I understand the basic concepts. I am able to do simple things like create controllers and services and views. However, I haven't made a foray into more advanced territory. Hence, I apologize if this question seems silly (or impossible).

I am wondering if there is a way to intercept the view and/or response and modify it before it gets sent to the client? I imagine this is how Spring performs data binding to form elements on the way out to the client. What I would like to do is inspect annotations on elements within a domain class and modify the view according to those annotations. This will involve injecting new code (HTML or Javascript) into the response.

UPDATE

As I thought about this a bit more, I realized that the final rendering is done by the JSP. So I guess the question is if there is a way to intercept the model before it moves out to the page and to figure out the annotations on the bean that the data is being bound to.

Is there a way to do this?

+2  A: 

Yes, a number of ways actually:

  • spring mvc interceptors (search for them in the mvc docs) - you can define the preHandle / postHandle methods and apply the interceptor to a number of controllers
  • spring aop - define an aspect to be executed before/after the methods of a given controller
  • servlet filters - this is the least desirable option, since it is not integrated with spring - you can't inject dependencies.
Bozho
+3  A: 

The class you're probably looking for is org.springframework.web.servlet.HandlerInterceptor You can implement the postHandle method on that interface and, as the signature implies, have access to both the request and the response, as well as the map of model objects that your controller created. (and the controller itself, that's what the Object handler parameter is.)

You 'turn them on' by adding them to the handler mapping in your dispatcher servlet.

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

Incidentally, binding is actually done inside the HandlerAdapter that locates Controller methods and invokes them, it's not an interceptor.

Edit: To answer your edit, yes this is where you have a chance to grab the model object and work with it more, after the controller is done, but before it goes to JSP rendering. So you could do something like add myCustomScript to the ModelMap and toss ${myCustomScript} in the <head> of your jsp, get a backing object out of the ModelMap and examine it, etc etc.

Affe
Thanks! This was what I was looking for.
Vivin Paliath