Question

I've got Spring HATEOAS working for accessing a specific resource, such as

http://localhost:8080/user/1

But I want to also be able to advertise a service url:

http://localhost:8080/user

For instance, if you do a GET / , I want to return the service resources I advertise. Right now the only one is /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);
}

Currently this is not compiling because linkTo doesn't take a void argument, which I presume is the return type of my authenticate method

What I WANT is this:

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

How do I accomplish this while staying within HATEOAS best practice?

Was it helpful?

Solution

This.

@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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top