我试图使用successfullAuthentication返回"UsernamePasswordAuthenticationFilter“中的”UsernamePasswordAuthenticationFilter“方法中的响应体,但返回的是这种格式的链接:
"links": [
{
"rel": "self",
"href": "http://localhost:8080/api/users/5c55ee26911e9f04acb77c91",
"hreflang": null,
"media": null,
"title": null,
"type": null,
"deprecation": null
},我希望它返回HAL格式,因此它看起来如下:
"_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(type ={ EnableHypermediaSupport.HypermediaType.HAL })中也有这样的内容。
有人知道为什么会这样吗?
发布于 2019-02-05 19:14:00
我在这个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;
}发布于 2019-02-05 17:29:53
尝试扩展所有模型类-添加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);https://stackoverflow.com/questions/54497308
复制相似问题