What is Spring Interceptor?

Spring Interceptor Interceptor performs similar role to Servlet Filter. Servlet filter provides functionality to intercept and process requests before and after they reach the servlet container. Spring Interceptor provides functionality to intercept and process requests before and after they reach the controller in Spring MVC. Interceptor is implemented using HandlerInterceptor interface. HandlerInterceptor interface provides three methods: preHandle: Method executed before the request reaches the controller postHandle: Method executed after the request has reached the controller, before the view is rendered afterCompletion: Method executed after the view has been rendered Interceptor Implementation 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CustomInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // Code to execute before the request reaches the controller // If false is returned, request is not forwarded to the controller return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // Code to execute after the controller is executed normally // Not executed if an exception is thrown } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // Code to execute after the view has been sent to the client // Exception object can be used to check exception information if an exception occurred // Exception information can be checked and logged } } Interceptor Registration To register the interceptor, implement the WebMvcConfigurer interface and override the addInterceptors method. ...

June 4, 2024 · 3 min · 567 words · In-Jun Hwang