타임리프를 처음 써보면서 잘 몰랐던 문법에 대해 정리해보고자 한다.
form
th:action
폼이 제출될 URL이나 경로를 지정하는 데 사용
ex) th:action="@{/fileBoard/insertProc}"는 폼 제출 대상을 /fileBoard/insertProc URL로 설정
th:object
폼이나 템플릿의 특정 부분과 객체를 연결하는 데 사용
폼의 데이터 모델로 사용할 객체를 지정
ex) th:object="${fileBoardVO}"는 fileBoardVO 객체를 폼과 연결하여 Thymeleaf가 폼 입력값을 fileBoardVO 객체의 해당 속성과 바인딩
th: field
th:field 속성은 폼 필드를 특정 객체 속성에 바인딩하는 데 사용
주로 <input>, <select>, <textarea>와 같은 폼 입력 요소에서 사용되며, 객체의 속성에 기반하여 name과 id 속성을 자동으로 생성
폼이 제출되면 폼 입력값은 자동으로 해당 객체 속성에 매핑되어 데이터 바인딩
ex) 주로 <input>, <select>, <textarea>와 같은 폼 입력 요소에서 사용되며, 객체의 속성에 기반하여 name과 id 속성을 자동으로 생성
사용 예시
/insert 경로로 요청이 들어오면 컨트롤러의 fileBoardInsertForm 메서드가 실행된다.
Controller
@RequestMapping("/insert")
private String fileBoardInsertForm(@ModelAttribute FileBoardVO board){
return "fileBoard/insert";
}
@ModelAttribute 어노테이션을 사용하여 FileBoardVO 객체를 매개변수로 받는다.
FileBoardVO 객체는 폼 데이터를 받아들이기 위해 사용되고, 이 객체를 템플릿에 전달하여 폼을 렌더링할 수 있다.
fileBoard/insert 뷰를 반환하여 클라이언트에게 보여준다.
아래와 같은 방법도 가능하다.
@RequestMapping("/insert")
private String fileBoardInsertForm(Model model){
model.addAttribute("fileBoardVO", new FileBoardVO());
return "fileBoard/insert";
}
Model 객체를 매개변수로 받고, Model 객체에 form data를 담을 비어있는 fileBoardVO 객체를 추가한다. 폼을 렌더링할 때 fileBoardVO라는 이름으로 fileBoardVO 객체를 사용할 수 있다.
insert.html
<form role="form" th:object="${fileBoardVO}" th:action="@{/fileBoard/insertProc}" method="post" enctype="multipart/form-data">
<div>
<label for="title" style="font-weight: bolder;">제목</label>
<input type="text" th:field="*{title}" id="title" name="title" placeholder="제목을 입력하세요" >
</div>
<div class="form-group">
<label for="writer" style="font-weight: bolder;">작성자</label>
<input type="text" th:field="*{writer}" id="writer" name="writer" placeholder="작성자를 입력하세요" >
</div>
<div class="form-group" style="font-weight: bolder;">
<label for="content">내용</label><br/>
<textarea th:field="*{content}" id="content" name="content" rows="15" cols="50" placeholder="내용을 입력하세요" ></textarea>
</div>
<div class="form-group">
<input type="file" name="files">
</div>
<div style="text-align: right;">
<button onclick="location.href='/fileBoard/list'">목록</button>
<input type="submit" th:value="작성">
<input type="reset" th:value="취소">
</div>
</form>
th:action으로 form data를 보낼 url을 지정한다.
th:object로 폼의 데이터 모델로 사용할 객체를 지정한다.
th:field에서는 받아온 객체의 필드변수 명을 입력해 form data를 보낼 때 자동으로 객체의 속성과 매핑되게 한다.
'BACK > SPRING' 카테고리의 다른 글
[Spring] 스프링 핵심 원리 - 객체 지향 원리 적용(+ DI, IoC, 스프링 컨테이너) (0) | 2024.01.30 |
---|---|
[Spring] 스프링 핵심 원리 - 객체 지향 설계와 스프링 (0) | 2024.01.30 |
[Spring] Servlet 동작 방식 (0) | 2023.05.23 |
스프링MVC - 웹 애플리케이션의 이해 (0) | 2023.02.12 |
Spring Boot Project(7) - 서비스 인증과 권한 부여 (0) | 2023.01.31 |