Junior — Middle
How does a router function in Java and what tasks does it solve?
sobes.tech AI
Answer from AI
In Java, a router is typically used in the context of web applications to route HTTP requests to the appropriate handlers (controllers). Its task is to determine which code should handle a specific request based on the URL, HTTP method, and other parameters.
For example, in the Spring MVC framework, the router maps URLs to methods annotated with @RequestMapping or @GetMapping.
Main tasks of the router:
- Analyze incoming requests
- Match the path and method with a handler
- Pass request parameters to the handler
- Support RESTful API
An example of simple routing using Spring Boot:
@RestController
public class MyController {
@GetMapping("/users/{id}")
public String getUser(@PathVariable String id) {
return "User ID: " + id;
}
}
Here, the router directs GET requests to the path /users/{id} to the getUser method.