How To Configure The Interceptor With Spring Boot Application

Posted By : Avnish Pandey | 31-Jan-2018

Interceptor :
In Spring, when any request comes from the browser and send to the controller then it has to go through the interceptors then it will go the controller. let us suppose if you go to any hotel then you have to pass through the gatekeeper of the hotel. So that we can say that the gatekeeper is the interceptor of the hotel. Spring Interceptor is similar to the servlet filter. Spring Interceptor is applicable on all requests that are sending to Spring controller.

 

In Spring if we want to do some task just before the request enters in the controller and just after response goes to the browser then we can create the Interceptor. We got the HandlerInterceptor interface and HandlerInterceptorAdapter class to create the interceptor. The interceptor must implement either HandlerInterceptor interface or extend HandlerInterceptorAdapter class.

Here is a program to create an Interceptor :

package com.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

@Component
public class CustomInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
		System.out.println("In preHandle method of Interceptor");
		System.out.println("Request URL :: " + req.getRequestURL());
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		System.out.println("In postHandle method of Interceptor");
		System.out.println("Request URL:: " + request.getRequestURL());
	}
}

Now we have to add the interceptor in the application :

 

package com.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class AppConfig extends WebMvcConfigurerAdapter {

	@Autowired
	CustomInterceptor customInterceptor;
	
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(customInterceptor);
	}
}

Thanks

 

About Author

Author Image
Avnish Pandey

Avnish has a good knowledge in core & advance Java, Spring and Hibernate Framework. He loves to learn new technologies.

Request for Proposal

Name is required

Comment is required

Sending message..