Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register handler interceptors with spring mvc 3.0?

It should be easy:

<bean id="handlerMapping"
   class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
    <property name="interceptors">
        <list>
            <ref bean="myInterceptor" />
        </list>
    </property>
</bean>

but this way the interceptor isn't called.

like image 457
Bozho Avatar asked Jul 12 '10 17:07

Bozho


People also ask

How do you implement a handler interceptor?

To work with interceptor, you need to create @Component class that supports it and it should implement the HandlerInterceptor interface. preHandle() method − This is used to perform operations before sending the request to the controller. This method should return true to return the response to the client.

What is Handler interceptor in Spring MVC?

Simply put, a Spring interceptor is a class that either extends the HandlerInterceptorAdapter class or implements the HandlerInterceptor interface. The HandlerInterceptor contains three main methods: prehandle() – called before the execution of the actual handler. postHandle() – called after the handler is executed.

Which interceptor is used in an application when maintenance page needs to be shown?

Spring Interceptor are used to intercept client requests and process them.


1 Answers

By default, Spring will register a BeanNameUrlHandlerMapping, and a DefaultAnnotationHandlerMapping, without any explicit config required.

If you define your own HandlerMapping beans, then the default ones will not be registered, and you'll just get the explicitly declared ones.

So far, so good.

The problem comes when you add <mvc:annotation-driven/> to the mix. This also declares its own DefaultAnnotationHandlerMapping, which replaces the defaults. However, if you also declare your own one, then you end up with two. Since they are consulted in order of declaration, this usually means the one registered by <mvc:annotation-driven/> gets called first, and your own one gets ignored.

It would be better if the DefaultAnnotationHandlerMapping registered by <mvc:annotation-driven/> acted like the default one, i.e. if explicitly declared ones took precedence, but that's not the way they wrote it.

My current preference is to not use <mvc:annotation-driven/> at all, it's too confusing, and too unpredictable when mixed with other config options. It doesn't really do anything especially complex, it's not difficult or verbose to explicitly add the stuff that it does for you, and the end result is easier to follow.

like image 197
skaffman Avatar answered Oct 10 '22 19:10

skaffman