在项目开发中,有时候我们需求在拦截器中获取@responsebody的返回值,但是在我的知识体系中没有方法获取,(除非研究源码),但是在springMVC4版本以后,新加了一个@ControllerService注解。用此注解然后实现ResponseBodyAdvice接口可获取带有@responsebody的返回值,然后操作。
然后在springmvc拦截器中afterCompletion的方法中进行获取。
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// 将handler强转化为handlermethod
HandlerMethod handlerMethod = (HandlerMethod) handler;
// 从方法处理器中获取要调用的方法
Method method = handlerMethod.getMethod();
//获取返回结果
Object result = request.getAttribute("response");
//获取当前类
Class> clazz = method.getDeclaringClass();
//获取当前的类名
String className = clazz.getName();
//获取当前的方法名
String methodName = method.getName();
//转化为json
String jsonResult = "";
if(result != null) {
jsonResult = JSON.toJSONString(result);
}
}