BackEnd/Thymeleaf

타임리프-입력 폼 처리

연향동큰손 2024. 7. 22. 16:59

타임리프와 스프링 통합으로 편리한 폼 관리가 가능하다.

 

 

th:object를 통해 폼에서 객체에 접근할 수 있도록 해줄 수 있다.

 

 

우선 컨트롤러에서 빈 오브젝트를 만들어서 뷰에 전달해줘야 한다.

@GetMapping("/add")
public String addForm(Model model) {
    model.addAttribute("item",new Item());
    return "form/addForm";
}

 

 

<editForm.html>

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <link th:href="@{/css/bootstrap.min.css}"
          href="../css/bootstrap.min.css" rel="stylesheet">
    <style>
        .container {
            max-width: 560px;
        }
    </style>
</head>
<body>

<div class="container">

    <div class="py-5 text-center">
        <h2>상품 수정 폼</h2>
    </div>

    <form action="item.html" th:action th: 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" name="price" class="form-control" th:field="*{price}">
        </div>
        <div>
            <label for="quantity">수량</label>
            <input type="text" id="quantity" name="quantity" class="form-control" value="10" th:field="*{quantity}" >
        </div>

        <hr class="my-4">

        <div class="row">
            <div class="col">
                <button class="w-100 btn btn-primary btn-lg" type="submit">저장</button>
            </div>
            <div class="col">
                <button class="w-100 btn btn-secondary btn-lg"
                        onclick="location.href='item.html'"
                        th:onclick="|location.href='@{/form/items/{itemId}(itemId=${item.id})}'|"
                        type="button">취소</button>
            </div>
        </div>

    </form>

</div> <!-- /container -->
</body>
</html>

위 상품 등록 폼 코드를 자세하게 살펴 보자.

 

 

th:object="${item}"을 통해 <form>에서 사용할 객체를 지정해준다.

<form action="item.html" th:action th:object="${item}" method="post">

 

그리고 th:field="*{변수}"를 통해 필드값을 받아올 수 있다.

<div>
    <label for="id">상품 ID</label>
    <input type="text" id="id"  class="form-control" th:field="*{id}" readonly>
</div>

 

 

랜더링 전 후 비교

 

<랜더링 전>

<label for="itemName">상품명</label>
<input type="text" id="itemName" th:field="*{itemName}" class="form-control">

 

 

<랜더링 후>

 

랜더링 후 th:field를 통해 자동으로 처리됨으로써 개발할때 편리함을 얻을 수 있다.