Spring Boot 返回加密后的 Response

Spring Boot About 1,091 words

ResponseBodyAdvice

实现ResponseBodyAdvice接口,在supports()方法中返回true会进入beforeBodyWrite(),在beforeBodyWrite()中对Controller中返回的对象Object body进行修改。

下面示例中的Response为自定义类。

@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ApiResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof Response || body instanceof ProblemDetail) {
            return body;
        }
        body = Response.builder().data(body).build();
        return body;
    }
}

Filter

doFilter()FilterChain调用filterChain.doFilter(request, response);之后再进行对HttpServletResponse读取流,进行修改。

Interceptor

postHandle()afterCompletion()方法中读取HttpServletResponse中的流进行修改。

Views: 1,326 · Posted: 2023-01-28

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh