The*_*ain 5 spring json spring-mvc
我正在使用 spring 框架构建 RESTful Web 服务。我发送的 JSON 响应包含图像 URL。图像 URL 在数据库中存储为相对路径,但为了避免客户端紧密耦合,我希望响应包含绝对 URL。
例如:而不是返回像这样的 json
{"username": "user123", "profile_picture": "/user123_profile.jpg"}
Run Code Online (Sandbox Code Playgroud)
我想返回一个像这样的json
{"username": "user123", "profile_picture": "http://example.com/user123_profile.jpg"}
Run Code Online (Sandbox Code Playgroud)
当然,图像字段可以位于响应中的任何位置,并且可以位于嵌套对象中。
拦截任何返回的响应并将图像字段转换为绝对 URL 的最佳位置是什么?
我想创建一个特殊的注释,例如@ImageURL图像字段,然后定义 a@ControllerAdvice并在方法中beforeBodyWrite(),我遍历所有字段,每当我找到带注释的字段时@ImageURL,我都会添加它的绝对路径。
这很有效,并且可以轻松定义新的图像字段,但每个请求/响应都会有很多反射,我认为这不好。
还有更好的建议吗?
这种问题在 Spring REST HATEOAS 解决的问题中似乎是精确的https://spring.io/guides/gs/rest-hateoas/
以下仅作为示例来说明 API 的工作原理(以此作为说明性示例,有关 Spring HATEOAS API 的具体详细信息请查看官方文档):
@RequestMapping(value="/user/{id}", method=RequestMethod.GET)
HttpEntity<MyUserResource> getUser( @PathVariable("id") long id )
{
MyUserResource resource = new MyUserResource( ... retrieve from db user data ... );
.
.
.
resource.add(linkTo(methodOn(MyServiceController.class).getProfilePicture( ...profile picture relative URL... )).withRel("profile_picture"));
.
.
.
return new ResponseEntity<MyUserResource>(resource, HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,我做出以下假设:控制器已命名MyServiceController,除了上面显示的用于检索用户数据的 GET 方法之外,它还有第二个getProfilePicture方法响应类似 的 URL GET "/user/{id}/profile_picture/{profile picture relative url}",返回实际的图像文件内容。
Spring REST HATEOAS 提供的方法(如 linkTo、methodOn 等)将负责生成绝对 URL 映射到后续对服务的 REST 调用。
因此,当调用http://example.com/myservice/user/123时,这将向客户端返回一个类似于以下内容的 JSON 对象:
{
"username":"user123",
"links": [
{
"rel": "profile_picture",
"href":"http://example.com/myservice/user/123/profile_picture/user123_profile.jpg"
}
]
}
Run Code Online (Sandbox Code Playgroud)
从这里,客户端将知道在 REST 服务上调用标记为 profile_picture 的 _link 来获取图像内容的绝对 URL。
| 归档时间: |
|
| 查看次数: |
1862 次 |
| 最近记录: |