Home > Archive > Spring & Spring Boots > ๐Ÿƒ[Spring] MVC์™€ ํ…œํ”Œ๋ฆฟ ์—”์ง„

๐Ÿƒ[Spring] MVC์™€ ํ…œํ”Œ๋ฆฟ ์—”์ง„
Spring Framework

MVC์™€ ํ…œํ”Œ๋ฆฟ ์—”์ง„

  • MVC: Model, View, Controller

Controller

package com.devkobe.hellospring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class HelloController {
    @GetMapping("hello-mvc")
    public String helloMvc(@RequestParam("name") String name, Model model) {
        model.addAttribute("name", name);
        return "hello-template";
    }
}

View

<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>

์‹คํ–‰

  • http://localhost:8080/hello-mvc?name=spring

MVC, ํ…œํ”Œ๋ฆฟ ์—”์ง„ ์ด๋ฏธ์ง€.

  1. ์›น ๋ธŒ๋ผ์šฐ์ €์—์„œ localhost:8080/hello-mvc๋ฅผ ๋„˜๊น๋‹ˆ๋‹ค.
  2. ์Šคํ”„๋ง ๋ถ€ํŠธ๋ฅผ ๋„์šธ ๋•Œ ํ•จ๊นจ ๋„์šฐ๋Š” โ€œ๋‚ด์žฅ ํ†ฐ์ผ“ ์„œ๋ฒ„๋ฅผ localhost:8080/hello-mvc ๊ฐ€ ๊ฑฐ์นฉ๋‹ˆ๋‹คโ€.
  3. ๋‚ด์žฅ ํ†ฐ์ผ“ ์„œ๋ฒ„๊ฐ€ โ€˜localhost:8080/hello-mvc๊ฐ€ ์™”์–ด~โ€™ ํ•˜๊ณ ๋Š” ์Šคํ”„๋ง์—๊ฒŒ ๋˜์ง‘๋‹ˆ๋‹ค.
  4. ๊ทธ๋Ÿฌ๋ฉด ์Šคํ”„๋ง์€ โ€˜์•„! localhost:8080/hello-mvc๊ฐ€ helloController ๋‚ด๋ถ€ ๋ฉ”์„œ๋“œ์— ๋งคํ•‘์ด ๋˜์–ด์žˆ๋„ค?!โ€™ํ•˜๊ณ ๋Š” โ€œ๊ทธ ๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœํ•ด์ค๋‹ˆ๋‹ค.โ€
  5. ํ˜ธ์ถœํ•œ ๋ฉ”์„œ๋“œ๊ฐ€ ๋ฆฌํ„ด์‹œ ์ด๋ฆ„์„ โ€œhello-templeโ€์ด๋ผ๊ณ  ํ•˜๊ณ , โ€œmodel์— ํ‚ค๋Š” name์ด๊ณ , ๊ฐ’์€ spring์œผ๋กœ ๋„ฃ์€๊ฒƒโ€์„ ์Šคํ”„๋ง์—๊ฒŒ ๋„˜๊ฒจ์ค๋‹ˆ๋‹ค.
  6. ๊ทธ๋Ÿฌ๋ฉด ์Šคํ”„๋ง์ด โ€œviewResolverโ€ (ํ™”๋ฉด๊ณผ ๊ด€๋ จ๋œ ํ•ด๊ฒฐ์ž - ๋ทฐ๋ฅผ ์ฐพ์•„์ฃผ๊ณ  ํ…œํ”Œ๋ฆฟ ์—”์ง„์„ ์—ฐ๊ฒฐ ์‹œ์ผœ์ฃผ๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค.)๊ฐ€ ๋™์ž‘ํ•ฉ๋‹ˆ๋‹ค.
  7. viewResolver๊ฐ€ โ€œtemplatesโ€ ์˜ โ€œhello-templateโ€ ์ด๋ผ๋Š” โ€œ๋ฆฌํ„ด์˜ String name๊ณผ ๋˜‘๊ฐ™์€ ์•„์ด๋ฅผ ์ฐพ์•„์„œ Thymeleaf ํ…œํ”Œ๋ฆฟ ์—”์ง„์—๊ฒŒ ์ฒ˜๋ฆฌํ•ด๋‹ฌ๋ผ๊ณ  ๋„˜๊น๋‹ˆ๋‹ค.โ€
  8. ๊ทธ๋Ÿฌ๋ฉด โ€œํ…œํ”Œ๋ฆฟ ์—”์ง„์ด ๋žœ๋”๋งโ€œ์„ ํ•˜์—ฌ โ€œ๋ณ€ํ™˜์„ ํ•œ HTMLโ€ ์„ โ€œ์›น ๋ธŒ๋ผ์šฐ์ €์— ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.โ€
  • ์ •์ ์ผ ๋•Œ๋Š” โ€œ๋ณ€ํ™˜์„ ํ•˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.โ€ ์ฆ‰, ๊ทธ๋Œ€๋กœ ๋ฐ˜ํ™˜์„ ํ•ด์คฌ์Šต๋‹ˆ๋‹ค.
    • ์ด๋Ÿฐ โ€œํ…œํ”Œ๋ฆฟ ์—”์ง„์—์„œ๋Š” ๋ณ€ํ™˜์„ํ•ด์„œ ์›น ๋ธŒ๋ผ์šฐ์ €์— ๋„˜๊ฒจ์ค๋‹ˆ๋‹ค.โ€