Spring 从HttpServletResponse返回HAL json
我正在尝试使用HATEOAS在“UsernamePasswordAuthenticationFilter”中的“successfullAuthentication”方法中返回响应正文,但正在以以下格式返回链接:Spring 从HttpServletResponse返回HAL json,spring,spring-boot,spring-security,spring-hateoas,Spring,Spring Boot,Spring Security,Spring Hateoas,我正在尝试使用HATEOAS在“UsernamePasswordAuthenticationFilter”中的“successfullAuthentication”方法中返回响应正文,但正在以以下格式返回链接: "links": [ { "rel": "self", "href": "http://localhost:8080/api/users/5c55ee26911e9f04acb77c91", "hreflang": null,
"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):
我的网络配置中也有这个:@EnableHypermediaSupport(type={EnableHypermediaSupport.HypermediaType.HAL})
有人知道为什么会发生这种情况吗?尝试扩展所有模型类-添加HATEOAS链接- 使用
org.springframework.hateoas.ResourceSupport类
假设控制器类中有各自的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);
参考:我在这个github问题上找到了答案: 基本上:
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;
}
感谢您的回答@JavaBuddy。但我的问题不是理解仇恨。当我在控制器中使用UserResource时,它工作正常。问题是,当我序列化UserResource以便从HttpServletResponse返回它时,它不是HAL格式。
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;
}