How can I register a Spring 3 JSON controller response with @ResponseBody in a HandlerInterceptorAdapter?

I have controllers that return JSON to the client. Controller methods are marked using the mvc annotation, for example:

@RequestMapping("/delete.me") public @ResponseBody Map<String, Object> delete(HttpServletRequest request, @RequestParam("ids[]") Integer[] ids) { 

Spring knows how to return JSON since Jackson is in the class path and the client requests a JSON response. I would like to register the response of these requests and all other controllers. I used to use an interceptor for this. However, I received the response body from ModelAndView. How can I get the response body in an inteceptor now that I am using @ResponseBody? In particular, how can I get the response body in this method?

 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { 
+4
source share
1 answer

You can record everything using a CustomizableTraceInterceptor you can either set it in the xml configuration of your application context, or use AOP: (log level trace)

  <bean id="customizableTraceInterceptor" class="org.springframework.aop.interceptor.CustomizableTraceInterceptor"> <property name="exitMessage" value="Leaving $[methodName](): $[returnValue]" /> </bean> 

or you can fully customize it by running it in Java and using the setExitMessage () method:

 public class TraceInterceptor extends CustomizableTraceInterceptor { private Logger log = LoggerFactory.getLogger("blabla"); @Override protected void writeToLog(Log logger, String message, Throwable ex) { //Write debug info when exception is thrown if (ex != null) { log.debug(message, ex); } .... } @Override protected boolean isInterceptorEnabled(MethodInvocation invocation, Log logger) { return true; } @Override public void setExitMessage(String exitMessage) { .... //Use PlaceHolders } } 

and use placeholders such as '$ [returnValue]'. A complete list can be found in the spring api documentation .

EDIT: Also, if you want to get the value of your @ResponseBody in another interceptor, I think this is not possible until version> 3.1.1. Check this issue: https://jira.springsource.org/browse/SPR-9226

+5
source

All Articles