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

时间:2014-09-20 18:10:46

标签: java image spring rest spring-mvc

我使用Spring和RepositoryRestResource创建REST服务器。我将图像名称存储在数据库中,并在其余响应中返回。我想发回整个网址而不仅仅是图片名称。

例如,在本地运行时,响应应为:

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

并且在部署到生产时,响应应该是

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

我目前得到的是:

{
  image: '1.jpg'
}

代码正是这里的内容:https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-data-rest,除了我有自己的模型

1 个答案:

答案 0 :(得分:0)

我刚遇到同样的问题,并了解到可以使用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对象包含来自rest endpoint的返回类型,您可以根据需要进行转换并对其进行修改。

相关问题