Spring Controller获取ResponseBody 对象

心血来潮想全局打印一下Controller请求入参,及返回。原本以为可以通过 HandlerInterceptorAdapter 拦截器获取,但是postHandle 不能获取返回类型是JSON的,ModelAndView  这种倒是可以获取。

 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

难道只能手写aop了吗?答案是No,Spring 内置一个ControllerAdvice 打上这个注解实现 ResponseBodyAdvice 接口就可以搞定啦。

 

package com.xuyw.core;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author one
 * @version v1.0
 * @description
 * @date 2020/3/24 16:29
 */
@ControllerAdvice
@Slf4j
public class MyResponseBodyAdvice implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        log.info("web 返回:{}", JSON.toJSONString(body));
        return body;
    }
}

 

你可能感兴趣的:(JAVA,spring)