Home > Enterprise >  Migrate HandlerInterceptor to Spring boot 2.6
Migrate HandlerInterceptor to Spring boot 2.6

Time:05-08

I have this old code implemented for Spring 2.4

public class Interceptor extends HandlerInterceptorAdapter {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
      Object handler) throws Exception {
    ........
    return super.preHandle(request, response, handler);
  }
}

I migrated the code to Spring 2.6:

public class Interceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
      Object handler) throws Exception {
    ......................
    return HandlerInterceptor.super.preHandle(request, response, handler);
  }
}

I got Cannot resolve method 'preHandle' in 'Object' so I change the code to HandlerInterceptor.super.preHandle(request, response, handler);

Is it correct to edit the code this way: HandlerInterceptor.super.preHandle(request, response, handler); or this should be edited another way?

CodePudding user response:

This should be

public class Interceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
      Object handler) throws Exception {
    ......................
    return true;
  }
}

Notice that the method returns a boolean value. It tells Spring to further process the request (true) or not (false).

The default implementation of preHandle() in HandlerInterceptor just returns true ( https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/HandlerInterceptor.html#preHandle-javax.servlet.http.HttpServletRequest-javax.servlet.http.HttpServletResponse-java.lang.Object- )

  • Related