스프링 MVC(Spring Model-View-Controller)에서 HTTP 요청과 응답은 웹 애플리케이션의 핵심 흐름 중 하나이다. 이 과정은 주로 다음과 같은 단계로 진행된다:
GET, POST, PUT, DELETE 등)와 함께 전송되며, URL, 헤더, 쿼리 파라미터, 본문(body) 등을 포함할 수 있다.DispatcherServlet이 요청을 가장 먼저 받는다.DispatchServlet은 HandlerMapping을 사용해 어떤 컨트롤러가 요청을 처리해야 하는지 결정한다.@RequestMapping, @GetMapping, @PostMapping 등의 어노테이션으로 설정된다.@Controller
public class MyController {
@GetMapping("/hello")
public String hello(Model model) {
model.addAttribute("message", "Hello, Spring MVC!");
return "hello"; // 뷰 이름 반환 (예: hello.jsp, hello.html)
}
}
Model에 담긴 데이터를 뷰로 전달하여 렌더링한다.200 OK, 404 Not Found 등), 헤더, 본문이 포함된다.[클라이언트 요청] → [DispatcherServlet] → [HandlerMapping] → [Controller] → [ViewResolver] → [View 렌더링] → [DispatcherServlet] → [클라이언트 응답]
@GetMapping("/greet")
public String greet(@RequestParam String name, Model model) {
model.addAttribute("name", name);
return "greeting";
}
@GetMapping("/user/{id}")
public String getUser(@PathVariable Long id, Model model) {
model.addAttribute("id", id);
return "userProfile";
}
@GetMapping("/api/data")
@ResponseBody
public Map<String, String> getData() {
return Map.of("key", "value");
}
이런 구조 덕분에 스프링 MVC는 웹 애플리케이션의 요청과 응답 처리를 깔끔하고 효율적으로 관리할 수 있다.