简体   繁体   English

Spring REST:在发送之前修改响应

[英]Spring REST: Modifying a response before sending

I'm using Spring and RepositoryRestResource to create a REST server. 我正在使用Spring和RepositoryRestResource创建REST服务器。 I store image names in the database and this is returned in the rest response. 我将图像名称存储在数据库中,这在其余响应中返回。 I'd like to send back the entire URL instead of just the image name. 我想发回整个URL,而不仅仅是图像名称。

For example, when running locally, the response should be: 例如,在本地运行时,响应应为:

{
  image: 'http://localhost:8080/img/products/1.jpg'
}

and when deploying to production, the response should be 当部署到生产环境时,响应应该是

{
  image: 'http://prod-server.com/img/products/1.jpg'
}

What I currently get is: 我现在得到的是:

{
  image: '1.jpg'
}

The code is exactly what is here: https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-data-rest except that I have my own Models 代码就是这里的代码: https : //github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-data-rest除了我有自己的模型

I have just encountered the same problem and learned that ResponseBodyAdvice can be used: 我刚刚遇到了相同的问题,并了解到可以使用ResponseBodyAdvice:

@RestControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {

@Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return returnType.getParameterType().isAssignableFrom(ResponseEntity.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        return body; // You can modify and return whatever you want.
    }
}

Body object contains your return type from rest endpoint, you can cast it and modify it as you like. Body对象包含您从其余端点返回的类型,您可以根据需要对其进行强制转换和修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM