[Spring] 5.ํ์ ๊ด๋ฆฌ ์์ - ์น MVC ๊ฐ๋ฐ
1. ํ์ ์น ๊ธฐ๋ฅ - ํ ํ๋ฉด ์ถ๊ฐ
- ํ ์ปจํธ๋กค๋ฌ ์ถ๊ฐ
ใด controller - HomeController
@Controller
public class HomeController {
@GetMapping("/")
public String home() {
return "home";
}
}
- ํ ํ๋ฉด ๋ง๋ค๊ธฐ
ใด resource - templates - home.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div class="container">
<div>
<h1>Hello Spring</h1>
<p>ํ์ ๊ธฐ๋ฅ</p>
<p>
<a href="/members/new">ํ์ ๊ฐ์
</a>
<a href="/members">ํ์ ๋ชฉ๋ก</a>
</p>
</div>
</div> <!-- /container -->
</body>
</html>
* ๋จผ์ ์์ฒญ์ด ์ค๋ฉด ๋งตํ๋ '/'์ด ์์ -> ๋ฐ๋ก ํด๋น ์ปจํธ๋กค๋ฌ ํธ์ถ๋๊ณ ๋๋จ
* static์ ์๋ index.html์ ํ์์ (์ ์ ๋ฆฌ์์ค์์๋)
2. ํ์ ์น ๊ธฐ๋ฅ - ๋ฑ๋ก
- memberController์ ๋งตํ ์ถ๊ฐ
@Controller
public class MemberController {
private MemberService memberService;
@Autowired
public MemberController(MemberService memberService) {
this.memberService = memberService;
}
@GetMapping("/members/new")
public String createForm() {
return "members/createMemberForm";
}
}
templates - members - createMemberForm.html
<!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>
Controller - MemberForm.class
public class MemberForm {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
ํ์ปจํธ๋กค๋ฌ
@PostMapping("/members/new")
public String create(MemberForm form) {
Member member = new Member();
member.setName(form.getName());
memberService.join(member);
return "redirect:/";
}
-> MemberForm (Argument Resolver์ ์ํด์ ์ฒ๋ฆฌ)
html์์ name์์ฑ๊ฐ๊ณผ MemberForm์ String name ์ด ์ผ์นํ๋ฉด MemberForm์ html์์ post๋ก ๋๊ฒจ์ค ๊ฐ์ด ๋ค์ด๊ฐ๊ฒ๋จ
(name = "name" ๋ฐ์ดํ ์์ name)
3. ํ์ ์น ๊ธฐ๋ฅ - ์กฐํ
- memberController์ ๋งตํ ์ถ๊ฐ
@GetMapping(value = "/members")
public String list(Model model) {
List<Member> members = memberService.findMembers();
model.addAttribute("members", members);
return "members/memberList";
}
memberList.html
<!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>
'๐จโ๐ป Web Development > Spring - Intro' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Spring] 7.AOP (0) | 2023.02.16 |
---|---|
[Spring] 6.์คํ๋ง DB ์ ๊ทผ ๊ธฐ์ (0) | 2023.02.14 |
[Spring] 4.์คํ๋ง ๋น๊ณผ ์์กด๊ด๊ณ (0) | 2023.02.11 |
[Spring] 3.ํ์๊ด๋ฆฌ ์์ - ๋ฐฑ์๋ ๊ฐ๋ฐ (0) | 2022.07.03 |
[Spring] 2.์คํ๋ง ์น ๊ฐ๋ฐ ๊ธฐ์ด (1) | 2022.07.01 |
์ต๊ทผ๋๊ธ