Thymeleaf

Thymeleaf ๋ฌธ๋ฒ• ์ •๋ฆฌ

keepgoing 2021. 12. 21. 18:53

th:field, th:error๐ŸŽˆ

th:field="{ํ•„๋“œ ์ด๋ฆ„}"์„ ์„ ์–ธํ•˜๋ฉด HTML์ด ๋ Œ๋”๋ง๋  ๋•Œ, id, name์„ ๊ฐ™์€ ๊ฐ’์œผ๋กœ ์ฒ˜๋ฆฌํ•ด์ค€๋‹ค.
์ฆ‰, `th:field="
{name}"์€id = "name" name = "name"`๊ณผ ๊ฐ™๋‹ค

//fieldError ๋ฉ”์†Œ๋“œ๋ฅผ ๋ฏธ๋ฆฌ ์„ ์–ธํ•ด์„œ ์—๋Ÿฌ ๋ฐœ์ƒ ์‹œ ๋นจ๊ฐ„์ƒ‰ ํ…Œ๋‘๋ฆฌ๊ฐ€ ํ˜ธ์ถœ๋˜๋„๋ก ์„ค์ •
<style>
 .fieldError {
 border-color: #bd2130;
 }
</style>
//th:field ์˜ˆ์‹œ
<input type="text" th:field="*{name}" class="form-control"
placeholder="์ด๋ฆ„์„ ์ž…๋ ฅํ•˜์„ธ์š”"
th:class="${#fields.hasErrors('name')}? 'form-control fieldError' : 'form-control'"> //ํ…Œ๋‘๋ฆฌ ๋นจ๊ฐ„์ƒ‰
<p th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Incorrect date</p>    //์—๋Ÿฌ๋ฉ”์‹œ์ง€ ์ถœ๋ ฅ

th:object๐ŸŽˆ

th:object๋Š” ํผ์—์„œ ์„œ๋ฒ„๋‹จ์œผ๋กœ ๊ฐ’์„ ๋„˜๊ธธ ๋•Œ object์— ์ง€์ •ํ•œ ๊ฐ์ฒด์— ๊ฐ’์„ ๋‹ด์•„ ๋„˜๊ฒจ์ค„ ์ˆ˜ ์žˆ๋‹ค. ์ฆ‰, ํ™”๋ฉด์—์„œ ์„ ์–ธํ•œ ๊ฐ์ฒด์— ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋œ๋‹ค.

//th:object ์˜ˆ์‹œ
<form role="form" action="/members/new" th:object="${memberForm}" //ํ™”๋ฉด์—์„œ memberForm ๊ฐ์ฒด์— ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋œ๋‹ค.
          method="post">

th:each๐ŸŽˆ

ํ•ด๋‹น ๊ฐ์ฒด์— ๋‹ด๊ธด ๊ฐ’๋“ค์„ ์ฝœ๋ ‰์…˜ ํ˜•์‹์œผ๋กœ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ๋‹ค.

//th:each ์˜ˆ์‹œ
<select name="memberId" id="member" class="form-control">
                <option value="">ํšŒ์›์„ ํƒ</option>
                <option th:each="member : ${members}"
                        th:value="${member.id}"
                        th:text="${member.name}" />
            </select>

'?'์˜ ์˜๋ฏธ

                <td th:text="${member.address?.city}"></td>

์œ„ ์ฝ”๋“œ์—์„œ address๋’ค์— '?'๊ฐ€ ์žˆ๋Š”๊ฑธ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋Š”๋ฐ ์—ฌ๊ธฐ์—์„œ ?์˜ ์˜๋ฏธ๋Š” null์ด ๋“ค์–ด๊ฐ€๋ฉด ๋”์ด์ƒ ์ง„ํ–‰ํ•˜์ง€ ์•Š๋Š”๋‹ค๋Š” ์˜๋ฏธ์ด๋‹ค.