Notice
Recent Posts
Recent Comments
Link
250x250
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 |
Tags
- 자바스크립트
- 프런트엔드
- Next.js
- web
- 백엔드
- 스프링부트
- jpa
- 알고리즘
- BACK-END
- 미니정리
- SQL
- 코드 테스트
- 오라클
- oracle
- JavaScript
- jsp
- spring
- 스프링
- 프로그래머스
- node.js
- 데이터베이스
- 정리
- 쿼리
- java
- 디자인 패턴
- MySQL
- 프론트엔드
- 자바
- 코드테스트
- 서버
Archives
- Today
- Total
참치코더의 꿈 메모장
Spring / Thymeleaf 폼(Form) 정리 - Spring MVC 연동 본문
728x90

Thymeleaf 폼이란
- Thymeleaf 폼은 HTML form 태그를 Spring MVC의 객체(Model)과 직접 바인딩하기 위한 기능이다.
- 입력값을 DTO(Form 객체)에 자동으로 매핑하고, 검증 결과 및 에러 메시지까지 쉽게 처리할 수 있다.
핵심 키워드
- th:object
- th:field
- @ModelAttribute
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
// Form 객체 (DTO) 예제
public class MemberForm {
private String name;
private Integer age;
// getter, setter
}
// Entity를 직접 사용하면 안된다. -> 항상 Form 전용 DTO를 사용해야 한다. (보안, 책임 분리 문제)
// Controller에서 폼 생성 (GET)
@GetMapping("/members/new")
public String form(@ModelAttribute("form") MemberForm form){
return "members/form";
}
// 1. MemberForm 객체 자동 생성
// 2. Model에 "form" 이름으로 등록
// 3. View에서 ${form} 사용 가능
// Thymeleaf 폼 기본 문법
// th:object
<form th:object="${form}" method="post">
// 이 폼이 어떤 객체와 연결되는지 지정
// 이후 필드들은 객체 기준으로 동작
// th:field
<input type="text" th:field="*{name}">
<input type="number" th:field="*{age}">
// 실제로 변환되는 HTML
<input type="text" name="name" value="">
<input type="number" name="age" value="">
// th:field 하나로 name, value, id를 자동 생성
// POST 요청 처리
@PostMapping("/members")
public String save(@ModelAttribute("form") MemberForm form) {
System.out.println(form.getName());
System.out.println(form.getAge());
return "result";
}
// 검증(Validation)과 폼
@PostMapping("/members")
public String save(@Valid @ModelAttribute("form") MemberForm form, BindingResult result){
if(result.hasErrors()){
return "members/form";
}
return "redirect:/"
}
|
cs |
728x90
'Spring' 카테고리의 다른 글
| Spring / Thymeleaf 라디오 버튼 & 셀렉트 박스 정리 (0) | 2026.01.23 |
|---|---|
| Thymeleaf / 단일 체크 박스, 다중 체크 박스 정리 (0) | 2026.01.19 |
| Spring / Thypeleaf 기본정리 (블록, 자바스크립트 인라인, 템플릿 조각) (0) | 2026.01.13 |
| Thymeleaf 기본 문법 정리 (연산, 속성 값 설정, 반복, 조건부 평가, 주석) (0) | 2026.01.12 |
| Spring / Thymeleaf 기본 문법 간단 미니 정리 (1) | 2026.01.02 |
Comments