How to get the return value of my controllers from HandlerInterceptor

I create a log manager for my controllers that logs every action in it and returns values

My controllers are defined as follows:

@Controller @RequestMapping(value="/ajax/user") public class UserController extends AbstractController{ @RequestMapping(value="/signup") public @ResponseBody ActionResponse signup(@Valid SignupModel sign) { ActionResponse response=new ActionRespone(); response.setMessage("This is a test message"); return response; } } 

and I defined a HandlerInterceptor to register the output of each handler:

 @Component public class ControllerInterceptor implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return true; } public void postHandle( HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { LogManager log=new LogManager(); log.setMessage();//I need returned ActionResponse here } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } } 

where i use log.setMessage (); I need my ActionResponse message (this is a test message) that is returned from the registration method

How can i do this?

+4
source share
1 answer

The interceptor is not suitable for doing what you need, since it is not able to get the return value of the handler.

You can achieve what you don't want without modifying existing code using aspect-oriented programming (AOP). For this to work in spring, you need to enable banks for spring-aop and AspectJ.

Create Aspect and Tips

 @Aspect @Component public class ActionResponseLoggerAspect { private static final Logger logger = LoggerFactory.getLogger(ActionResponseLoggerAspect.class); @AfterReturning(pointcut="execution(* your.package.UserController.*(..)))", returning="result") public void afterReturning(JoinPoint joinPoint , Object result) { if (result instanceof ActionResponse) { ActionResponse m = (ActionResponse) result; logger.info("ActionResponse returned with message [{}]", m.getMessage()); } } } 

The afterReturning method will be executed each time the controller method is returned.

Enabling @AspectJ Support

Enable AspectJ support by adding this to your XML configuration.

 <aop:aspectj-autoproxy></aop:aspectj-autoproxy> 

See the spring docs for more information.

+3
source

Source: https://habr.com/ru/post/1492980/


All Articles