Sobes.tech
Junior — Middle

How can you extract the resource identifier from a URL inside a controller method?

sobes.tech AI

Answer from AI

In Java, for example in Spring MVC, the @PathVariable annotation is used to extract the resource identifier from the URL within a controller method. It allows you to obtain a value from the request path and use it as a method parameter.

Example:

@GetMapping("/users/{id}")
public ResponseEntity<User> getUserById(@PathVariable("id") Long userId) {
    // userId will contain the value from the URL
    User user = userService.findById(userId);
    return ResponseEntity.ok(user);
}

Here, {id} is part of the URL that will be extracted and passed to the userId parameter of the controller method.