Junior — Middle
How to implement web request handling using Spring MVC?
sobes.tech AI
Answer from AI
In Spring MVC, web request processing is implemented through controllers that accept HTTP requests and return responses.
Main steps:
- Create a class with the
@Controlleror@RestControllerannotation. - Use the
@RequestMappingannotation (or specialized ones like@GetMapping,@PostMapping) to specify the URL and HTTP method. - In controller methods, accept request parameters and return data or views.
Example controller:
@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello(@RequestParam(name = "name", defaultValue = "World") String name) {
return "Hello, " + name + "!";
}
}
In this example, a GET request to /hello?name=Ivan will return the string "Hello, Ivan!".