본문 바로가기
프로그래밍언어/Java

[Spring boot] 타임리프 입력 폼 처리

by Yikanghee 2022. 2. 10.
  • 값을 컨트롤 단으로 넘길때 기존 html에서는 name, id, value를 입력해야만 값이 들어간다
  • 타임리프에서는 form 태그에 th:object=”${}” 를 추가해주고 그 뒤에 입력 받을 input 태그에 **th:field=”*{}”**를 입력해주면 위에 내용을 자동으로 생성해준다
  • 먼저 Controller 단에서 model값을 view에 넘겨준다
@GetMapping("/add")
public String addForm(Model model) {
    model.addAttribute("item", new Item());
    return "form/addForm";
}
  • 뷰에서는 th:objectth:field로 값을 받아올수있다
    <form action="item.html" th:action th:object="${item}" method="post">
        <div>
            <label for="id">상품 ID</label>
            <input type="text" id="id" class="form-control" th:field="*{id}" readonly>
        </div>
        <div>
            <label for="itemName">상품명</label>
            <input type="text" id="itemName" class="form-control" th:field="*{itemName}">
        </div>
        <div>
            <label for="price">가격</label>
            <input type="text" id="price" class="form-control" th:field="*{price}">
        </div>
        <div>
            <label for="quantity">수량</label>
            <input type="text" id="quantity" class="form-control" th:field="*{quantity}">
        </div>
    ​

댓글