์น MVC ๊ฐ๋ฐ
1. ํ์ ์น ๊ธฐ๋ฅ
1) ํ ํ๋ฉด ์ถ๊ฐ
- ์ปจํธ๋กค๋ฌ๊ฐ ์ ์ ํ์ผ๋ณด๋ค ์ฐ์ ์์๊ฐ ๋๋ค.
- ์ฆ, ์ฐ์ปด ํ์ด์ง(index.html)๊ฐ ์์ด๋ ์ปจํธ๋กค๋ฌ๊ฐ ์กด์ฌํ๋ค๋ฉด ์ ์ ํ์ด์ง๋ ๋ฌด์๋๋ค.
package hello.hello.spring.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HomeController {
@GetMapping("/")
public String home() {
return "home";
}
}
2) ํ์ ๋ฑ๋ก
- form: ๊ฐ์ ์ ๋ ฅํ ์ ์๋ HTML ํ๊ทธ์ด๋ค.
- ์๋ ์ฝ๋๋ ๋ฑ๋ก ๋ฒํผ์ ๋๋ฅด๋ฉด action URL๋ก post ๋ฐฉ์์ ํตํด name์ ๋๊ธด๋ค๋ ๋ง์ด๋ค.
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div class="container">
<form action="/members/new" method="post">
<div class="form-group">
<label for="name">์ด๋ฆ</label>
<input type="text" id="name" name="name" placeholder="์ด๋ฆ์
์
๋ ฅํ์ธ์">
</div>
<button type="submit">๋ฑ๋ก</button>
</form>
</div> <!-- /container -->
</body>
</html>
package hello.hello.spring.controller;
public class MemberForm {
// createMemberForm์ name๊ณผ ๋งคํ๋๋ค.
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- @GetMapping: URI(URL)๊ฐ ๊ฐ์ง ์ ๋ณด๋ฅผ ๊ฒ์(์กฐํ) ํ๊ธฐ ์ํด ์๋ฒ ์ธก์ ์์ฒญํ๋ ํํ์ด๋ค.
- @PostMapping: HTML์ FORM ๊ตฌ์ฑ ์์(ํน์ ๋ฉ์์ง ๋ณธ๋ฌธ)๋ฅผ ์ด์ฉํด ๋ฐ์ดํฐ ์ ์กํ ๋ ์ฃผ๋ก ์ฌ์ฉํ๋ค.
package hello.hello.spring.controller;
import hello.hello.spring.domain.Member;
import hello.hello.spring.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class MemberController {
private final MemberService memberService;
@Autowired
public MemberController(MemberService memberService) {
this.memberService = memberService;
}
@GetMapping("/members/new")
public String createForm() {
return "members/createMemberForm";
}
@PostMapping("/members/new")
public String create(MemberForm form) {
Member member = new Member();
member.setName(form.getName());
memberService.join(member);
// ๋ค์ ํ ํ๋ฉด์ผ๋ก ๋์๊ฐ๋ค.
return "redirect:/";
}
}
3) ํ์ ์กฐํ
- members๋ฅผ ๋ชจ๋ ๋ชจ๋ธ์ ๋ด์ ํ๋ฉด์ ๋๊ธฐ๋ ๋์์ด๋ค.
@GetMapping("/members")
public String list(Model model) {
List<Member> members = memberService.findMembers();
model.addAttribute("members", members);
return "members/memberList";
}
- thymeleaf๊ฐ ๋ณธ๊ฒฉ์ ์ผ๋ก ๋์ํ๊ฒ ๋๋ค.
- ๋ชจ๋ธ ์์ ๋ด๊ธด members๋ฅผ ๊บผ๋ด ํ๋์ฉ ๊ฐ์ฒด๋ฅผ ๋๋ฉฐ id์ name์ ์ถ๋ ฅํ๋ค.
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div class="container">
<div>
<table>
<thead>
<tr>
<th>#</th>
<th>์ด๋ฆ</th>
</tr>
</thead>
<tbody>
<tr th:each="member : ${members}">
<td th:text="${member.id}"></td>
<td th:text="${member.name}"></td>
</tr>
</tbody>
</table>
</div>
</div> <!-- /container -->
</body>
</html>