jiwhiz
jiwhiz

Reputation: 87

How to build HAL links with "templated:true" using Spring-hateoas?

I'm trying to figure out how to build HAL links with templated: true. If I use

BasicLinkBuilder.linkToCurrentMapping().slash("api/public/blogs/{blog}").withRel("blog");

The { and } chars are still encoded. Any idea how to build template URL links with Spring-hateo as 0.10.0.RELEASE by its API?

Thanks.

Upvotes: 6

Views: 4567

Answers (2)

Maciej Walkowiak
Maciej Walkowiak

Reputation: 12932

To get brackets in links I've ended up with a bit hacky solution, but as a temporal workaround works:

  • create class:
public class BracketsLink extends Link {
    public BracketsLink(Link link) {
        super(link.getHref().replaceAll("%7B", "{").replaceAll("%7D", "}"), link.getRel());
    }
}
  • and create links using BracketsLink class:
new BracketsLink(linkTo(methodOn(MessageController.class).message("{id}")).withRel("message"))

Upvotes: 1

Ross Taylor-Turner
Ross Taylor-Turner

Reputation: 3765

I'm also wondering how this is meant to be done using the HATEOAS API. For now we've worked around it by generating the Link objects using the BasicLinkBuilder and ControllerLinkBuilder classes, and then appending templated query params into a new Link(String href) constructor. Interestingly, this builds a Link with a templated: true attribute.

We noticed that attempting to pass in values such as {blog} into the LinkBuilder classes ended in these values attempting to be replaced from values on the current request (i.e. the linkbuilder was attempting to find ?blog=value from the current request and replace value into the Link being built, and as this didn't exist was causing an exception.

Although the workaround isn't particularly nice my team hasn't been able to find any way of getting templated params into the LinkBuilders via the API without causing problems.

Upvotes: 3

Related Questions