springboot快速入门-10.实现全局拦截返回值并修改

前提条件

一般建议用于有统一的返回值类时(例如本例中用的Result.java)

新建全局拦截类

在interceptor文件夹中新建一个全局拦截返回值类:MyResponseBodyAdvice.java
代码如下

package com.example.demo.base.interceptor;

import com.example.demo.base.vo.Result;
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.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 全局拦截返回值
 * @author DaenMax
 */
@ControllerAdvice
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) {
        //形如:/love/user/test2
        String requestPath = request.getURI().getPath();
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession httpSession = httpServletRequest.getSession(true);

        //可以在此处修改body,实现全局拦截返回结果修改后返回
        //Result result = (Result) body;
        //result.setCode(100);
        //body = result;

        //放到缓存里,以便于可以在HandlerInterceptor拦截里取出并打印出返回结果
        httpSession.setAttribute("body", body);
        return body;
    }
}

这样就实现了全局拦截到并修改后返回

日志打印

在拦截器MyInterceptor.java中的afterCompletion方法下新增两行代码,如下

    /**
     * 在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //取出在ResponseBodyAdvice中设置的body
        Result result = (Result) request.getSession().getAttribute("body");
        System.out.println("即将返回->" + result.toJsonString());
    }
上一篇:Java Validation Api


下一篇:offsetTop、offsetParent