简体   繁体   中英

Using Spring how do I get contents of HttpServletResponse in postHandle interceptor and in case of error redirect

All my controllers return JSON response. As part of post handling how do I examine contents of JSON response and in case of errors how do I redirect. Thanks for your help.

The JSON operations in Spring are based on MappingJacksonHttpMessageConverter. If you want to log the result, extend it and override the write method OR use an aspect on this method:

@Aspect
 public class MyLogger {

   @Pointcut("execution(org.springframework.http.converter.AbstractHttpMessageConverter.write(..))")
   public void myPointCut() { }

   @AfterReturning(pointcut="myPointCut()",returning="result")
   public void logMethodEntry(JoinPoint jp) {
      ...
   }

}

To manage erors, you can use the ExceptionHandler annotation on your methods/classes:

@ExceptionHandler(YourException.class)
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public Map<String, String> notFoundHandler(Exception e){
    return ...;
}

I hope this will help ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM