Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring mvc 在Spring Hateoas中将链接分解为实体_Spring Mvc_Spring Boot_Spring Hateoas - Fatal编程技术网

Spring mvc 在Spring Hateoas中将链接分解为实体

Spring mvc 在Spring Hateoas中将链接分解为实体,spring-mvc,spring-boot,spring-hateoas,Spring Mvc,Spring Boot,Spring Hateoas,也许另一个人偶然发现了这个话题,并找到了一个很好的解决方案。在Spring HATEOAS项目的帮助下,使用HATEOAS REST方法可以很好地构建到资源的链接。但最后,为了将扁平化的资源映射回实体对象树,我需要分解我的链接并查询持久化后端。举个例子,我有一个实体项,引用ItemType(多对一)。item的自然键是ItemType外键和item代码本身的组合。使用链接生成器在ItemController中映射的URL为 @RequestMapping("/catalog/items/{ite

也许另一个人偶然发现了这个话题,并找到了一个很好的解决方案。在Spring HATEOAS项目的帮助下,使用HATEOAS REST方法可以很好地构建到资源的链接。但最后,为了将扁平化的资源映射回实体对象树,我需要分解我的链接并查询持久化后端。举个例子,我有一个实体项,引用ItemType(多对一)。item的自然键是ItemType外键和item代码本身的组合。使用链接生成器在ItemController中映射的URL为

@RequestMapping("/catalog/items/{itemTypeCode}_{itemCode}")
现在,一个项目的唯一链接是

为了反转此链接,我做了一些非常难看的字符串工作:

@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;
}

我一直在想,是否有更好、更灵活的方法(注意任何查询字符串部分,这会破坏代码)来进行这种反向映射。实际上,我不想从一个控制器中调用另一个MVC控制器,但最好是以某种方式利用dispatcher servlet反汇编函数将URL解构为更方便使用的内容。有什么有用的提示吗?Thx很多:)

您可以使用
UriTemplate
。它的
match
方法返回从URI中提取的变量及其值的映射。例如:

UriTemplate-UriTemplate=newuritemplate(“/catalog/items/{itemTypeCode}}{itemCode}”);
映射变量=uriTemplate.match(“http://www.sample.com/catalog/items/p_abc123");
字符串itemTypeCode=变量。获取(“itemTypeCode”);//“p”
String itemCode=variables.get(“itemCode”);//“abc123”