SpringBoot 使用 RequestBodyAdviceAdapter 和 ResponseBodyAdvice 对请求和响应做标识 使用RequestContextHolder新增线程变量

发布时间 2024-01-08 13:41:20作者: JserSuper

 

@ControllerAdvice
public class RequestBodyAdapter extends RequestBodyAdviceAdapter {
    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return "com.test.Jxy".equals(targetType.getTypeName());
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
                                Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter,
                                           Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        String str = "";
        try {
            InputStream body = inputMessage.getBody();
            str = StreamUtils.copyToString(body, StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String json = "";
        if (str.contains("__REQUEST2__")) {
            ..
            RequestContextHolder.getRequestAttributes().setAttribute("__N__", "T", RequestAttributes.SCOPE_REQUEST);
        } else {
            ..
            json = JsonUtil.toJson(info);
        }

        InputStream inputStream = new ByteArrayInputStream(json.getBytes());
        return new HttpInputMessage() {
            @Override
            public InputStream getBody() {
                return inputStream;
            }

            @Override
            public HttpHeaders getHeaders() {
                return inputMessage.getHeaders();
            }
        };
    }
}

 

@ControllerAdvice
public class ResponseBodyAdapter implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        if (body != null && body.getClass().equals(EIInfo.class)) {
            // 从RequestAttributes中获取来源标识
            String source = (String) RequestContextHolder.getRequestAttributes().getAttribute("__N__", RequestAttributes.SCOPE_REQUEST);

            if ("T".equals(source)) {
                ..
            }
            return body;
        } else {
            return body;
        }
    }
}