如何在Spring(Boot)中修饰REST响应? [英] How can I decorate the REST response in Spring (Boot)?

查看:280
本文介绍了如何在Spring(Boot)中修饰REST响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Spring Boot应用程序,它返回被编码为JSON响应的各种对象,我想对它们进行后处理并向某些超类添加信息。

I've got a Spring Boot application that returns various objects that get encoded as JSON responses and I'd like to post-process them and add information to certain super classes.

在用Jackson编码为JSON之前,有没有办法过滤,拦截等来自我的REST端点的对象响应。

Is there a way to filter, intercept, etc. the object responses from my REST endpoints before they get encoded to JSON with Jackson.

过滤器不起作用,因为它在 HttpServlet {Request,Response} 级别运行。

A filter won't work since it operates at the HttpServlet{Request,Response} level.

推荐答案

我猜 ResponseBodyAdvice 是你的朋友。基本上它:

I guess ResponseBodyAdvice is your friend. Basically it:


允许在执行
@ResponseBody ResponseEntity 控制器方法但在使用 HttpMessageConverter 写入
正文之前。
实现可以直接注册
RequestMappingHandlerAdapter ExceptionHandlerExceptionResolver
更可能用 @ControllerAdvice 进行注释,在这种情况下,两者都会自动检测

Allows customizing the response after the execution of an @ResponseBody or a ResponseEntity controller method but before the body is written with an HttpMessageConverter. Implementations may be may be registered directly with RequestMappingHandlerAdapter and ExceptionHandlerExceptionResolver or more likely annotated with @ControllerAdvice in which case they will be auto-detected by both.

这里我拦截所有返回的 String s并将它们设为大写:

Here i'm intercepting all the returned Strings and make them uppercase:

@ControllerAdvice
public class MyResponseBodyAdvisor implements ResponseBodyAdvice<String> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return returnType.getParameterType().equals(String.class);
    }

    @Override
    public String beforeBodyWrite(String body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        return body.toUpperCase();
    }
}

这篇关于如何在Spring(Boot)中修饰REST响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆