Monday, January 4, 2016

What is Spring MVC Interceptor and how to use it?

Ref:- http://howtodoinjava.com/2015/03/02/spring-mvc-interview-questions-with-answers/

As you know about servlet filters that they can pre-handle and post-handle every web request they serve — before and after it’s handled by that servlet. In the similar way, you can use HandlerInterceptor interface in your spring mvc application to pre-handle and post-handle web requests that are handled by Spring MVC controllers. These handlers are mostly used to manipulate the model attributes returned/submitted they are passed to the views/controllers.
A handler interceptor can be registered for particular URL mappings, so it only intercepts requests mapped to certain URLs. Each handler interceptor must implement the HandlerInterceptor interface, which contains three callback methods for you to implement: preHandle()postHandle() and afterCompletion().
Problem with HandlerInterceptor interface is that your new class will have to implement all three methods irrespective of whether it is needed or not. To avoid overriding, you can use HandlerInterceptorAdapter class. This class implementsHandlerInterceptor and provide default blank implementations.

No comments:

Post a Comment