【问题标题】:Spring HATEOAS: How to advertise resource services?Spring HATEOAS:如何宣传资源服务?
【发布时间】:2014-01-08 20:14:33
【问题描述】:

我已经让 Spring HATEOAS 用于访问特定资源,例如

http://localhost:8080/user/1

但我也希望能够宣传服务网址:

http://localhost:8080/user

例如,如果您执行 GET / ,我想返回我宣传的服务资源。目前唯一的一个是 /auth。

@RequestMapping(value = "/", method = RequestMethod.GET)
@ResponseBody
public HttpEntity<AuthenticationResource> post() {
    AuthenticationResource resource = new AuthenticationResource();
    resource.add(linkTo(methodOn(AuthenticationController.class).authenticate()).withSelfRel());
    return new ResponseEntity<AuthenticationResource>(resource, HttpStatus.OK);
}

@RequestMapping(value = "/auth", method = RequestMethod.POST, consumes = "application/json")
@ResponseBody
public void authenticate() {
    //users.save(user);
}

目前这没有编译,因为 linkTo 不接受 void 参数,我认为这是我的身份验证方法的返回类型

我想要的是这个:

{"links":[{"rel":"someString","href":"http://localhost/auth"}]}

如何在遵守 HATEOAS 最佳实践的同时实现这一目标?

【问题讨论】:

    标签: spring rest spring-mvc spring-hateoas


    【解决方案1】:

    这个。

    @RequestMapping(value = "/", method = RequestMethod.GET)
    @ResponseBody
    public HttpEntity<ResourceSupport> post() {
        ResourceSupport resource = new ResourceSupport();
        resource.add(linkTo(methodOn(AuthenticationController.class).authenticate()).withRel("authenticate"));
        return new ResponseEntity<ResourceSupport>(resource, HttpStatus.OK);
    }
    
    @RequestMapping(value = "/auth", method = RequestMethod.POST, consumes = "application/json")
    @ResponseBody
    public HttpEntity<AuthenticationResource> authenticate() {
        AuthenticationResourceAssembler assembler = new AuthenticationResourceAssembler();
        AuthenticationResource resource = assembler.toResource(new Authentication());
    
        return new ResponseEntity<AuthenticationResource>(resource, HttpStatus.OK);
    }
    

    【讨论】:

    • 这与您的问题无关,但您应该注入 Autowired AuthenticationResourceAssembler 而不是在每个 POST 上创建...
    猜你喜欢
    • 2015-12-03
    • 2014-11-09
    • 1970-01-01
    • 2016-11-05
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2011-04-14
    相关资源
    最近更新 更多