从HttpServletResponse返回HAL json

时间:2019-02-02 20:40:53

标签: spring spring-boot spring-security spring-hateoas

我正在尝试使用HATEOAS在“ UsernamePasswordAuthenticationFilter”中的“ successfullAuthentication”方法中返回响应正文,但正在以以下格式返回链接:

"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(type = {EnableHypermediaSupport.HypermediaType.HAL})

有人知道为什么会这样吗?

2 个答案:

答案 0 :(得分:1)

我在这个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;
}

答案 1 :(得分:0)

尝试扩展所有模型类-添加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://spring.io/understanding/HATEOAS