Parse object references in Spring Hateoas

perhaps another stumbled upon this topic and found a pleasant solution. Using the HATEOAS REST Approach with Spring The HATEOAS project works very well for building resource references. But in the end, in order to map flattened resources back to the entity object tree, I need to parse my link and request support. The above example, I have an Item object referencing ItemType (many-to-one). The natural key of an element is the combination of the ItemType foreign key and the element code itself. Map URL in ItemController using link builder -

@RequestMapping("/catalog/items/{itemTypeCode}_{itemCode}")

Now a unique link for an item is, for example, http://www.sample.com/catalog/items/p_abc123

To invert this link, I am doing a very ugly line job:

@Override
public Item fromLink(Link link) {
    Assert.notNull(link);
    String baseLink = linkTo(ColorTypeController.class).toString() + "/";
    String itemTypeAndItemPart = link.getHref().replace(baseLink, "");
    int indexOfSplit = itemTypeAndItemPart.indexOf('_');
    ItemType itemType = new ItemType();
    itemType.setCode(itemTypeAndItemPart.substring(0, indexOfSplit));
    Item item = new Item();
    item.setItemType(itemType);
    item.setCode(itemTypeAndItemPart.substring(indexOfSplit + 1));
    return item;
}

And all the time, I wonder if there is no more pleasant and flexible approach (beware of any part of the query string that breaks the code) to do this reverse mapping. Actually, I don’t want to call another MVC from the controller, but it would be nice to somehow use the functions of disassembling dispatcher servlets to deconstruct the URL into something more convenient for work. Any helpful tips for me? thanks alot :)

+4
source share
1 answer

UriTemplate. match , URI. :

UriTemplate uriTemplate = new UriTemplate("/catalog/items/{itemTypeCode}_{itemCode}");
Map<String, String> variables = uriTemplate.match("http://www.sample.com/catalog/items/p_abc123");
String itemTypeCode = variables.get("itemTypeCode"); // "p"
String itemCode = variables.get("itemCode"); // "abc123"
+6

All Articles