Sobes.tech
Junior — Middle

How does a controller determine which method to handle based on the HTTP request?

sobes.tech AI

Answer from AI

In Java web frameworks (such as Spring MVC), controllers use annotations to map HTTP requests to methods.

Main mechanism:

  • Annotations, such as @GetMapping, @PostMapping, or @RequestMapping, specify the path and HTTP method.
  • When a request arrives, the framework analyzes the URL and HTTP method.
  • It finds the controller method with the appropriate annotation matching the request path and method.
  • It invokes this method to handle the request.

Example:

@RestController
@RequestMapping("/users")
public class UserController {

    @GetMapping("/{id}")
    public User getUser(@PathVariable String id) {
        // handle GET /users/{id}
        return userService.findById(id);
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        // handle POST /users
        return userService.save(user);
    }
}

Here, a GET request to /users/123 will invoke the getUser method, and a POST to /users will invoke createUser. The framework automatically parses the HTTP request and determines the appropriate method.

How does a controller determine which method to… - sobes.tech