首页 > 解决方案 > Spring Boot GetMapping 的反向 URL 解析

问题描述

我目前正在编写 Spring Boot REST API,并希望对GetMapping. 在 Django Web 框架中,有一种方法可以做到这一点:reverse。但我无法为 Spring Boot 找到类似的东西。

我正在寻找这样的东西:

package help.me.stack.overflow;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("api")
public class SomeController {

    @GetMapping(value = "/items/{filter}/blob")
    public ResponseEntity<?> getItems(@PathVariable String filter, @RequestParam String sorting) {
        return ResponseEntity.ok().body("here you go");
    }

    @GetMapping(value = "/give-me-url")
    public ResponseEntity<?> getTheUrl() {
        return resolveUrl(SomeController.getItems, "foo-filter", "foo-sorting");
        // should produce "api/items/foo-filter/blob?sorting=foo-sorting"
    }
}

存在这样的东西吗?我该如何使用它?

标签: javadjangospringspring-booturl

解决方案


是的,您可以WebMvcLinkBuilder.linkTo(...)从 Spring HATEOAS 使用:

linkTo(methodOn(SomeController.class).getItems("foo-filter", "foo-sorting")).withSelfRel()

有关更多示例,请参见此处


推荐阅读