Reputation: 4171
How can I get the matched request path in an HTTP mapping method in a spring application? In the following example, I want matchedPath
variable to have the value /api/products/{product_id}/comments
which is a combination of @RequestMapping
and @PostMapping
value.
@RestController
@RequestMapping("/api")
public class Example {
@PostMapping("/products/{product_id}/comments")
public ResponseEntity doSomething(@PathVariable("product_id") String id) {
// String matchedPath = getPath();
return ResponseEntity.ok().build();
}
}
Upvotes: 1
Views: 2390
Reputation: 4171
I found it is doable via one of HandlerMapping
attributes BEST_MATCHING_PATTERN_ATTRIBUTE
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("/api")
public class Example {
@PostMapping("/products/{product_id}/comments")
public ResponseEntity doSomething(HttpServletRequest req, @PathVariable("product_id") String id) {
String matchedPath = String.valueOf(req.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE));
return ResponseEntity.ok().build();
}
}
Upvotes: 1