簡體   English   中英

反向 URL 分辨率為 Spring 引導 GetMapping

[英]Reverse URL resolution for Spring Boot GetMapping

I am currently writing a Spring Boot REST API and wanted to do a reverse resolution of a URL that is defined in a 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"
    }
}

存在這樣的東西嗎? 我該如何使用它?

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

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

有關更多示例,請參見此處

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM