Home > OS >  URI within endpoint
URI within endpoint

Time:07-29

I have a URI string inside the request that I am supposed to make. How to extract it and write a proper controller.

markerURI = marker://markerType/markerValue

Request: POST /books/123/markers/marker://big/yellow

I have written below rest controller for the above request:

@PostMapping("/books/{id}/markers/{markerURI:^marker.*}") 
public void assignMarker(
    @PathVariable("id") String id,
    @PathVariable("markerURI") String markerURI
)

but i'm not able to get markerURI=marker://big/yellow inside markerURI variable. The request show 404 Not found error. Is there any way to do this. It's a requirement so can't do any hacks.

Edit: markerURI can contain attributes like marker://markerType/markerValue?attr1=val1&attr2=val2

CodePudding user response:

As per https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-requestmapping-uri-templates

You can have your url pattern in below pattern

"/resources/ima?e.png" - match one character in a path segment

"/resources/*.png" - match zero or more characters in a path segment

"/resources/**" - match multiple path segments

"/projects/{project}/versions" - match a path segment and capture it as a variable

"/projects/{project:[a-z] }/versions" - match and capture a variable with a regex

but your url pattern is defined as a url inside a url, for that I suggest you to use below method and concatenate your result after fetching the values from uri as pathvariable.

@PostMapping("/books/{id}/markers/{marker:[a-z] }://{markerType:[a-z] }/{markerValue:[a-z] }")
public void assignMarker(@PathVariable("id") String id,@PathVariable("marker") String marker,
                         @PathVariable("markerType") String markerType,
                         @PathVariable("markerValue") String markerValue) {

    String markerUri = "/" marker "://" markerType "/" markerValue;
    System.out.println(markerUri);

}
  • Related