我想在“UsernamePasswordAuthenticationFilter”我“successfullAuthentication”方法使用HATEOAS返回响应体,但返回以这种格式的链接:
"links": [
{
"rel": "self",
"href": "http://localhost:8080/api/users/5c55ee26911e9f04acb77c91",
"hreflang": null,
"media": null,
"title": null,
"type": null,
"deprecation": null
},
我想它返回HAL JSON格式因此它看起来像这样:
"_links": {
"self": {
"href": "http://localhost:8080/api/users/5c55ee26911e9f04acb77c91"
},
我有这个在我的方法(反应是HttpServletResponse的):
User user = userService.findById(authResult.getName());
String json = Jackson.toJsonString(userResourceAssembler.toResource(user));
response.setContentType("application/hal+json");
response.setCharacterEncoding("UTF-8");
response.addHeader(jwtConfig.getHeader(), jwtConfig.getPrefix() + token);
response.getWriter().write(json);
我也有这个在我的WebConfig:@EnableHypermediaSupport(类型= {} EnableHypermediaSupport.HypermediaType.HAL)
有谁知道为什么发生这种情况?
我发现在这个问题GitHub的答案:https://github.com/spring-projects/spring-hateoas/issues/270#issuecomment-145606558
基本上:
private String convertToHalString(ResourceSupport resource) {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new Jackson2HalModule());
mapper.setHandlerInstantiator(new Jackson2HalModule.HalHandlerInstantiator(
new EvoInflectorRelProvider(), null, null));
String resourceString = null;
try {
resourceString = mapper.writeValueAsString(resource);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return resourceString;
}
尽量延长所有的模型类 - 添加HATEOAS链接 -
与org.springframework.hateoas.ResourceSupport class
假设你有相应的URI在控制器类
Link link = ControllerLinkBuilder
.linkTo(UserController.class)
.slash(user.getXXX())
.withSelfRel();
//for single resource
user.add(link);
Link userLink = ControllerLinkBuilder
.linkTo(ControllerLinkBuilder
.methodOn(UserController.class).getAllUsers())
.withSelfRel();
//For collections
userList.add(userLink);