Search code examples
spring-bootservlet-filtersservlet-3.0

How to know which Rest controller method called using HttpServletRequest or HttpServletResponse object?


I am using HandlerInterceptor (import org.springframework.web.servlet.HandlerInterceptor;) to get the Request and Response Attributes and Header information using preHandle, postHandle methods.

Now I want to know the name of the method called of Controller. Is there any way if we can get that info using HttpServletRequest or HttpServletResponse object ?


Solution

  • We need to use Object handler to get the details of method invocation. See the below code:

    @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                ModelAndView modelAndView) throws Exception {
    

    and

    public static String getMethodName(Object handler) {
            String methodName = null;
            if(handler instanceof HandlerMethod) {
                HandlerMethod method = (HandlerMethod) handler;
                methodName = method.getMethod().getName();
            }
            return methodName;
        }