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

2

6

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.

Discernible answered 12/4, 2014 at 15:23 Comment(1)
i too am wondering this..further you'll note if you look at your response that includes that Link that the { and } will have been url escaped...which isn't rightFlagship
Q
3

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.

Quimby answered 22/5, 2014 at 15:36 Comment(3)
I am using UriTemplate to construct a templated URI and then pass to new Link(). See my blog jiwhiz.com/post/2014/4/… and my open source project at github.com/jiwhiz/JiwhizBlogWeb. I hope Spring HATEOAS can provide more formal API to do that.Discernible
That's pretty much the same place my team has come to as wellQuimby
@Discernible I'm doing pretty much the same as you described. Problem appears to be that ControllerLinkBuilder uses the org.springframework.web.util.UriTemplate which doesn't allow for unresolved variables. There is a org.springframework.hateoas.UriTemplate that seems to do the job but then the links when rendered are missing templated: true attribute even though in the debugger I see the Link.isTemplated method returning true. Also the links are rendered relative because the builder class that prepends the context path et. al is package scope in ControllerLinkBuilder.Ecker
I
1

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"))
Imbroglio answered 12/1, 2015 at 8:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.