Wednesday, 21 February 2018

What is the usage and how to use the Interceptors ?


Interceptor can be used to avoid repetitive handler code (parameter change, logging etc.)

DispatcherServlet uses HandlerAdaptor to invoke the method.
HandlerInterceptor can perform action :
  • before handling
  • after handling
  • after completion (on rendering the view)

CREATING INTERCEPTOR
1. implement HandlerInterceptor interface
have to implement all 3 methods : prehandle() , postHandle(), afterCompletion()
OR
2. extend HandlerInterceptorAdapter class
have to implement only 1 method : prehandle()


@Configuration
public class MyInterceptor extends HandlerInterceptorAdapter {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
        System.out.println("Inside Interceptor - preHandle() ...");

        // You can access and manipulate the request and response objects here ...
        return true;
    }
}



REGISTERING INTERCEPTOR
1. Extend the main class with WebMvcConfigurerAdapter class.
2. Override the method addInterceptors and register all the interceptors in registry object.

@SpringBootApplication
public class TrainingApplication extends WebMvcConfigurerAdapter {

    @Resource
    private MyInterceptor myInterceptor;
   
    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(TrainingApplication.class, args);
    }
   
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor).addPathPatterns("/emp");
    }
}



When you request using the defined pattern (Example : http://localhost:8080/emp), this interceptor will be called.
If you do not add any addPathPatterns method call, interceptor will be called for each path.


No comments:

Post a Comment

Note: only a member of this blog may post a comment.