Intercept the view/response in Spring MVC 3

前端 未结 2 1594
野趣味
野趣味 2021-01-13 10:39

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

相关标签:
2条回答
  • 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.
    0 讨论(0)
  • 2021-01-13 11:27

    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.

    0 讨论(0)
提交回复
热议问题