The HandlerInterceptor interface has a parameter Object handler, which means implementing code has to do type checking on the handler object in order to use it, and cast it as appropriate.
Code snippets I've found seem to assume the handler is always a HandlerMethod object and return true if this isn't the case, but I want to understand why this seems to be a common implementation to make a robust implementation.
A standard way of implementing this interface seems to be:
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
if (handler instanceof HandlerMethod) {
// ...
return x; // whether or not to proceed with execution
}
return true; // fallback value in case handler wasn't a HandlerMethod
}
}
The Spring javadoc seems to ignore the fact that the interface has an Object type in it, it's very unhelpful for my understanding of this interface.
Some questions that might aid my understanding of how this interface is supposed to be implemented:
- Why is
truea sensible default if we get a handler that's not the object we expect it to be? - Which types can an
HandlerInterceptortake for itshandlerparameter? - Under what circumstances could
handlerbe a different type, if any? - Why is it an
Object, not aHandlerMethod, parameter?