Spring MVC ๊ฐ์
๐ ๊ฐ์
- Spring MVC๋ Spring Framework๊ฐ ์ ๊ณตํ๋ Servlet API ๊ธฐ๋ฐ ์น ์ ํ๋ฆฌ์ผ์ด์ ํ๋ ์์ํฌ์ด๋ค.
- MVC ํจํด๊ณผ Front Controller ํจํด์ ๊ตฌํํ์ฌ ์์ฒญ ํ๋ฆ์ ์ค์์์ ์ ์ดํ๊ณ , ๊ด์ฌ์ฌ๋ฅผ ๋ถ๋ฆฌํ๋ค.
- ํต์ฌ ๊ตฌ์ฑ์์์ธ DispatcherServlet์ด ๋ชจ๋ HTTP ์์ฒญ์ ๋ฐ์ ์ปจํธ๋กค๋ฌ๋ก ์์ํ๊ณ , ์๋ต์ ์์ฑํ๋ค.
- MVC ํจํด (Model - View - Controller)
- Front Controller ํจํด - ์์ฒญ์ ํ๋ฆ์ ์ค์ ์ง์ค์์ผ๋ก ๊ด๋ฆฌ (๊ณตํต ๊ธฐ๋ฅ ์ฒ๋ฆฌ: ์ธ์ฆ, ์ธ๊ฐ ๋ฑ)
โ๐ป ํ์ค ์์ฝ
Spring MVC๋ DispatcherServlet์ ์ค์ฌ์ผ๋ก ํ MVC ์ํคํ ์ฒ๋ก, ์์ฒญ์ ์ค์ ์ง์ค์ ์ผ๋ก ๊ด๋ฆฌํ๊ณ ์ปจํธ๋กค๋ฌยท๋ทฐยท๋ชจ๋ธ์ ๋ช ํํ ๋ถ๋ฆฌํ๋ค.
๐ค ์ ํ์ํ๊ฐ?
- ์๋ธ๋ฆฟ/JSP ๊ธฐ๋ฐ ๊ฐ๋ฐ ์ ๋ฐ์ํ๋ ์ค๋ณต ์ฝ๋(์์ฒญ/์๋ต ์ฒ๋ฆฌ, ํ๋ผ๋ฏธํฐ ํ์ฑ, ๋ทฐ ๋ ๋๋ง)๋ฅผ ์ ๊ฑฐ
- ์์ฒญ ํ๋ฆ์ ์ผ๊ด๋ ๋ฐฉ์์ผ๋ก ๊ด๋ฆฌ ๊ฐ๋ฅ
- ์ ์ฐํ ํ์ฅ์ฑ: ์ธํฐ์ ํฐ, ํํฐ, ๋ทฐ ๋ฆฌ์กธ๋ฒ ๋ฑ์ผ๋ก ๊ธฐ๋ฅ ์ถ๊ฐ๊ฐ ์ฉ์ด
โ๏ธ ํต์ฌ ๊ตฌ์ฑ ์์
DispatcherServlet
- ๋ชจ๋ ์์ฒญ์ ๋ฐ์ ์ปจํธ๋กค๋ฌ๋ก ์ ๋ฌํ๋ Front Controller
- ํธ๋ค๋ฌ ๋งคํ, ํธ๋ค๋ฌ ์ด๋ํฐ, ๋ทฐ ๋ฆฌ์กธ๋ฒ ๋ฑ์ ํตํด ์์ฒญ-์๋ต ์ฒ๋ฆฌ
WebMvcAutoConfiguration
- Spring Boot์์ ๊ธฐ๋ณธ์ ์ธ MVC ์ปดํฌ๋ํธ๋ฅผ ์๋ ์ค์
EnableWebMvcConfiguration
- ์ฃผ์ ๋น ์์ฑ ๋ฐ ์ค์ :
RequestMappingHandlerMapping
RequestMappingHandlerAdapter
WebMvcConfigurer
- MVC ์ค์ ์ ์ปค์คํฐ๋ง์ด์งํ๋ ์ธํฐํ์ด์ค
- ๋ฉ์๋ ์ข
๋ฅ:
addXxx()
: ์๋ก์ด ๋น/์ค์ ์ถ๊ฐconfigureXxx()
: ๊ธฐ์กด ์ค์ ๋ณ๊ฒฝ
๐ @SpringBootApplication
- Spring Boot ์ ํ๋ฆฌ์ผ์ด์
์ ์์์ ์ด๋ฉฐ, ๋ค์์ ํฌํจ:
@Configuration
: Bean ๋ฑ๋ก ์ค์ ํด๋์ค@ComponentScan
: ์ปดํฌ๋ํธ ์ค์บ@EnableAutoConfiguration
: ์๋ ์ค์ ํ์ฑํ
๐ฎ Controller
@Controller
- ์์ฒญ์ ์ฒ๋ฆฌํ๊ณ View ์ด๋ฆ์ ๋ฐํํ๋ ์ปดํฌ๋ํธ
@Controller
public class HomeController {
@GetMapping("/")
public String index() {
return "index";
}
}
@RequestMapping
๊ณ์ด ์ ๋
ธํ
์ด์
- URL, HTTP Method, ์กฐ๊ฑด ๋ฑ์ ๋ฐ๋ผ ๋ฉ์๋ ๋งคํ
- ์ถ์ฝํ:
@GetMapping
,@PostMapping
,@PutMapping
,@DeleteMapping
@GetMapping("/persons/{id}")
public Person getPerson(@PathVariable Long id) { ... }
๐ฆ Model & ํ๋ผ๋ฏธํฐ ์ฒ๋ฆฌ
๋ชจ๋ธ ๊ฐ์ฒด
Model
,Map
,ModelMap
์ฌ์ฉ ๊ฐ๋ฅ- ๋ทฐ์ ๋ฐ์ดํฐ ์ ๋ฌ
@GetMapping("/user")
public String getUsers(Model model) {
model.addAttribute("users", userRepository.getUsers());
return "users";
}
ํ๋ผ๋ฏธํฐ ๋ฐ์ธ๋ฉ
@RequestParam
: ์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ ์์@PathVariable
: URL ๊ฒฝ๋ก ๋ณ์ ๋ฐ์ธ๋ฉ@RequestHeader
,@CookieValue
: HTTP ํค๋, ์ฟ ํค ๊ฐ ์ฝ๊ธฐ@ModelAttribute
: ์์ฒญ ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ฒด์ ์๋ ๋ฐ์ธ๋ฉ
โ ๏ธ ์ฃผ์ํ ์
@Controller
๋ ๊ธฐ๋ณธ์ ์ผ๋ก ๋ทฐ ๋ฐํ, API ์๋ต ์@RestController
๋๋@ResponseBody
์ฌ์ฉ@ModelAttribute
์@RequestBody
๋ ๋ชฉ์ ์ด ๋ค๋ฆ:@ModelAttribute
: ํผ ๋ฐ์ดํฐ/์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ โ ๊ฐ์ฒด@RequestBody
: JSON/XML ์์ฒญ ๋ฐ๋ โ ๊ฐ์ฒด
- Spring Boot๋ ๊ธฐ๋ณธ์ ์ผ๋ก
DispatcherServlet
์ด/
๊ฒฝ๋ก์ ๋งคํ๋จ