${...}
: 변수 표현식 *{...}
: 선택 변수표현식 #{...}
: 메시지 표현식 @{...}
: 링크 URL 표현식 ~{...}
: 조각 표현식'one text'
, 'two text'
, ···0
, 34
, 3.0
true
, false
null
+
|The Name is ${name}|
-
, +
, -
, *
, /
, %
and
, or
, !
, not
>
(gt), <
(lt), >=
(ge), <=
(le)==
(eq), !=
(ne)if-then
, if-then-else
<span th:text="${data}"></span>
[[${data}]]
<java>
@GetMapping("text-basic")
public String textBasic(Model model) {
model.addAttribute("data","<b>Hello spring!!</b>");
return "basic/text-basic";
}
<html>
<body>
<h1>컨텐츠에 데이터 출력하기</h1>
<ul>
<li>th:text 사용 : <span th:text="${data}"></span></li>
<li>컨텐츠 안에서 직접 출력하기 = [[${data}]]</li>
</ul>
</body>
👍 결과
<span th:utext="${data}"></span>
<span th:inline="none">[(...)]</span> [(${data})]
<java>
@GetMapping("text-unescaped")
public String textUnescaped(Model model) {
model.addAttribute("data", "<b>Hello Spring!!</b>");
return "basic/text-unescaped";
}
<html>
<body>
<h1>text vs utext</h1>
<ul>
<li>th:text = <span th:text="${data}"></span> </li>
<li>th:utext = <span th:utext="${data}"></span> </li>
</ul>
<h1>
<span th:inline="none">[[...]] vs [(...)]</span>
</h1>
<ul>
<li><span th:inline="none">[[...]]</span> [[${data}]] </li>
<li><span th:inline="none">[(...)]</span> [(${data})] </li>
</ul>
</body>
👍 결과
${객체.변수이름}
: "${user.username}">
${객체['변수이름']}
: ${user['username']}
${객체.get변수이름()}
: ${user.getUsername()}
${리스트이름[i].변수이름}
: ${users[0].username}
${리스트이름[i]['변수이름']}
: ${users[0]['username']}
${리스트이름[i].get변수이름()}
: ${users[0].getUsername()}
${맵이름['키값'].변수이름}
: ${userMap['userA'].username}
${맵이름['키값']['변수이름']}
: ${userMap['userA']['username']}
${맵이름['키값'].get변수이름()}
: <${userMap['userA'].getUsername()}
<div th:with="first=${users[0]}"></div>
<span th:text=${first.username}></span>
💡 예시
// 객체 만들기
public class User {
private String username;
private int age;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public User(String username, int age) {
super();
this.username = username;
this.age = age;
}
// controller
@GetMapping("variable")
public String textVariable (Model model) {
User userA = new User("userA", 10);
User userB = new User("userB", 20);
List<User> list = new ArrayList<>();
list.add(userA);
list.add(userB);
Map<String, User> map = new HashMap<>();
map.put("userA", userA);
map.put("userB", userB);
model.addAttribute("user",userA);
model.addAttribute("users",list);
model.addAttribute("userMap",map);
return "basic/variable
}
<body>
<h1>Spring EL표현식</h1>
<ul>Object
<li>
${user.username} = <span th:text="${user.username}"></span>
</li>
<li>
${user['username']} = <span th:text="${user['username']}"></span>
</li>
<li>
${user.getUsername()} = <span th:text="${user.getUsername()}"></span>
</li>
</ul>
<ul>
List
<li>
${users[0].username} = <span th:text="${users[0].username}"></span>
</li>
<li>
${users[0]['username']} = <span th:text="${users[0]['username']}"></span>
</li>
<li>
${users[0].getUsername()} = <span th:text="${users[0].getUsername()}"></span>
</li>
</ul>
<ul>
Map
<li>
${userMap['userA'].username} = <span th:text="${userMap['userA'].username}"></span>
</li>
<li>
${userMap['userA']['username']} = <span th:text="${userMap['userA']['username']}"></span>
</li>
<li>
${userMap['userA'].getUsername()} = <span th:text="${userMap['userA'].getUsername()}"></span>
</li>
</ul>
<h1>지역변수 - (th:with)</h1>
<!-- 변수로 리스트 할당 -->
<div th:with="first=${users[0]}">
<p>
처음 사람의 이름은
<span th:text=${first.username}></span>
</p>
</div>
</body>
👍 결과
${#request}
, ${#response}
, ${#session}
, ${#servletContext}
, ${#locale}
${#request.getParameter('파라미터 이름')}
, ${param.파라미터 이름}
${session.key값}
${@객체이름.메서드이름('파라미터')}
: ${@helloBean.hello('user')}
💡 편의 객체 예시
// 파라미터용
<a href="basic/basic-objects?paramData=HelloParam"></a>
// 세션용
@GetMapping("/basic-objects")
public String basicObjects(HttpSession session) {
session.setAttribute("sessionData", "hello");
return "basic/basic-objects";
}
// HelloBean.java
@Component("helloBean")
public class HelloBean {
public String hello(String data) {
return "spring data : " + data;
}
}
<body>
<h1>편의 객체</h1>
<ul>
<li>
Request Parameter = <span th:text="${#request.getParameter('paramData')}"></span>
</li>
<li>
Request Parameter2 = <span th:text="${param.paramData}"></span>
</li>
<li>
session = <span th:text="${session.sessionData}"></span>
</li>
<li>
<!-- hellobean의 메소드 hello에 변수user을 대입 -->
spring bean = <span th:text="${@helloBean.hello('user')}"></span>
</li>
</ul>
</body>
👍 결과
${localDateTime}
${#temporals.format(localDateTime, 'yyyy-MM-dd HH:mm:ss')}
${#temporals.format(localDateTime, 'yyyy-MM-dd')}
${#temporals.year(localDateTime)}
${#temporals.month(localDateTime)}
${#temporals.day(localDateTime)}
${#temporals.dayOfWeek(localDateTime)}
@GetMapping("/date")
public String basicDate(Model model) {
model.addAttribute("localDateTime", LocalDateTime.now());
return "basic/date";
}
<body>
<h1>LocalDateTime</h1>
<ul>
<li>default = <span th:text="${localDateTime}"></span></li>
<li>yyyy-MM-dd HH:mm:ss =
<span th:text="${#temporals.format(localDateTime, 'yyyy-MM-dd HH:mm:ss')}"></span></li>
<li>yyyy-MM-dd =
<span th:text="${#temporals.format(localDateTime, 'yyyy-MM-dd')}"></span></li>
<li>MM/dd =
<span th:text="${#temporals.format(localDateTime, 'MM/dd')}"></span></li>
</ul>
<h1>LocalDateTime - Utils</h1>
<ul>
<li>${#temporals.day(localDateTime)} =
<span th:text="${#temporals.day(localDateTime)}"></span>
</li>
<li>${#temporals.month(localDateTime)} =
<span th:text="${#temporals.month(localDateTime)}"></span>
</li>
<li>${#temporals.monthName(localDateTime)} =
<span th:text="${#temporals.monthName(localDateTime)}"></span>
</li>
<li>${#temporals.monthNameShort(localDateTime)} =
<span th:text="${#temporals.monthNameShort(localDateTime)}"></span>
</li>
<li>${#temporals.year(localDateTime)} =
<span th:text="${#temporals.year(localDateTime)}"></span>
</li>
<li>${#temporals.dayOfWeek(localDateTime)} =
<span th:text="${#temporals.dayOfWeek(localDateTime)}"></span>
</li>
<li>${#temporals.dayOfWeekName(localDateTime)} =
<span th:text="${#temporals.dayOfWeekName(localDateTime)}"></span>
</li>
<li>${#temporals.dayOfWeekNameShort(localDateTime)} =
<span th:text="${#temporals.dayOfWeekNameShort(localDateTime)}"></span>
</li>
<li>${#temporals.hour(localDateTime)} =
<span th:text="${#temporals.hour(localDateTime)}"></span>
</li>
<li>${#temporals.minute(localDateTime)} =
<span th:text="${#temporals.minute(localDateTime)}"></span>
</li>
<li>${#temporals.second(localDateTime)} =
<span th:text="${#temporals.second(localDateTime)}"></span>
</li>
<li>${#temporals.nanosecond(localDateTime)} =
<span th:text="${#temporals.nanosecond(localDateTime)}"></span>
</li>
</ul>
</body>
👍 결과
th:href="@{/hello}"
http://localhost:9090/hello
th:href=@{/hello(param1=${param1}, param2=${param2})}
@GetMapping("/link")
public String basicLink(Model model) {
model.addAttribute("param1","data1");
model.addAttribute("param2","data2");
return "basic/link";
}
/hello?param1=data1¶m2=data2
th:href="@{/hello/{param1}/{param2}(param1=${param1},param2=${param2})}
http://localhost:9090/hello/data1/data2
th:href="@{/hello/{param1}(param1=${param1},param2=${param2})}
http://localhost:9090/hello/data1?param2=data2
""
(큰 따옴표) 안에 ''
(작은 따옴표)로 표현th:text="'hello' + ' world'"
th:text="'hello world'"
th:text="hello"
th:text="'hello ' + ${data}"
||
를 사용하면 작은 따옴표와 +
를 대체할 수 있다."|hello ${data}|"
<span th:text="10 + 2"></span>
<span th:text="1 >= 10"></span>
<span th:text="(10 % 2 == 0)?'짝수':'홀수'"></span>"
@GetMapping("/operation")
public String basicOperation(Model model) {
model.addAttribute("data","Spring");
model.addAttribute("nullData", null);
return "basic/operation";
}
<span th:text="${data}?:'데이터가 없습니다.'"></span>
th:text="${nullData}?:'데이터가 없습니다.'"
<span th:text="${data}?:_">데이터가 없습니다.</span>
<span th:text="${nullData}?:_">데이터가 없습니다.</span>
th:*
<input type="text" name="mock" th:name="userA">
th:attrappend
<input type="text" class="text" th:attrappend="class='large'">
class="textlarge"
th:attrprepend
<input type="text" class="text" th:attrprepend="class='large'">
class="largetext"
th:classappend
<input type="text" class="text" th:classappend="large">
class="text large"
checked O
<input type="text" class="text" th:attrappend="class='large'">
checked X
<input type="checkbox" name="active" th:checked="false">
checked = false
<input type="checkbox" name="active" checked="false">
💡 예시
@GetMapping("/each")
public String basicEach(Model model) {
addUsers(model);
return "basic/each";
}
private void addUsers(Model model) {
List<User> list = new ArrayList<>();
list.add(new User("userA", 10));
list.add(new User("userB", 20));
list.add(new User("userC", 30));
model.addAttribute("users", list);
}
<table border="1">
<tr>
<th>username</th>
<th>age</th>
</tr>
<!-- arraylist 이름 users를 user이름 아래 하나씩 담아줌 -->
<tr th:each="user : ${users}">
<td th:text="${user.username}">username</td>
<td th:text="${user.age}">0</td>
</tr>
</table>
👍 결과
반복의 상태
확인 가능💡 예시
<table border="1">
<tr>
<th>count</th>
<th>username</th>
<th>age</th>
<th>etc</th>
</tr>
<tr th:each="user, userStat : ${users}">
<td th:text="${userStat.count}"></td>
<td th:text="${user.username}"></td>
<td th:text="${user.age}"></td>
<td>
index = <span th:text="${userStat.index}"></span>
count = <span th:text="${userStat.count}"></span>
size = <span th:text="${userStat.size}"></span>
even = <span th:text="${userStat.even}"></span>
odd = <span th:text="${userStat.odd}"></span>
first = <span th:text="${userStat.first}"></span>
last = <span th:text="${userStat.last}"></span>
</td>
</tr>
</table>
👍 결과
if
: 만약 ~ 한다면unless
: 만약 ~ 하지 않는다면💡 예시
<table border = "1">
<tr>
<th>count</th>
<th>username</th>
<th>age</th>
</tr>
<tr th:each="user, userStat : ${users}">
<td th:text="${userStat.count}"></td>
<td th:text="${user.username}"></td>
<td>
<span th:text="${user.age}"></span>
<span th:text="'미성년자'" th:if="${user.age lt 20}"></span>
<span th:text="'미성년자'" th:unless="${user.age ge 20}"></span>
</td>
</tr>
</table>
👍 결과
💡 렌더링 예시
<span th:text="'미성년자'" th:unless="${user.age ge 20}"></span>
<span th:text="'성인'" th:unless="${user.age lt 20}"></span>
👍 결과
💡 예시
<table border="1">
<tr>
<th>count</th>
<th>username</th>
<th>age</th>
</tr>
<tr th:each="user,userStat : ${users}">
<td th:text="${userStat.count}"></td>
<td th:text="${user.username}"></td>
<td th:switch=${user.age}>
<span th:case="10">10살</span>
<span th:case="20">20살</span>
<span th:case="*">기타</span>
</td>
</tr>
</table>
👍 결과
<!-- -->
<!--/* 내용 */-->
<!--/* -->
내용 <!-- */-->
<!--/*
내용 */-->
💡 예시
<th:block th:each="user : ${users}">
<div>
사용자 이름1<span th:text="${user.username}"></span>
사용자 나이1<span th:text="${user.age}"></span>
</div>
<div>
요약<span th:text="${user.username} +'/' + ${user.age}"></span>
</div>
</th:block>
👍 결과
💡 예시
@GetMapping("/javascript")
public String basicJavascript(Model model) {
model.addAttribute("user", new User("userD", 40));
addUsers(model);
return "basic/javascript";
}
<script th:inline="javascript">
let username = [[${user.username}]];
let age = [[${user.age}]];
</script>
👍 결과(페이지 소스보기)
<script>
let username = "userD";
let age = 40;
</script>
/*[[${객체.변수이름}]]*/ "test"
💡 예시
<script th:inline="javascript">
let username2 = /*[[${user.username}]]*/ "test username";
</script>
👍 결과(페이지 소스보기)
<script>
// 자바스크립트 내추럴 템플릿
let username2 = "userD";
</script>
💡 예시
<script th:inline="javascript">
let user = [[${user}]];
</script>
👍 결과(페이지 소스보기)
<script>
// 객체
let user = {"username":"userD","age":40};
</script>
💡 예시
<script th:inline="javascript">
/*<![CDATA[*/
[# th:each="user, stat : ${users}"]
let user[[${stat.count}]] = [[${user}]];
[/]
/*]]>*/
</script>
👍 결과(페이지 소스보기)
<script>
/*<![CDATA[*/
let user1 = {"username":"userA","age":10};
let user2 = {"username":"userB","age":20};
let user3 = {"username":"userC","age":30};
/*]]>*/
</script>
th:fragment
💡 예시
<footer th:fragment="copy">
footer 자리 입니다.
</footer>
<footer th:fragment="copyParam(param1,param2)">
<p>파라미터 자리입니다.</p>
<p th:text="${param1}"></p>
<p th:text="${param2}"></p>
</footer>
💡 예시
<h2>부분 포함 insert</h2>
<div th:insert="~{template/fragment/footer :: copy}"></div>
👍 결과(페이지 소스보기)
<h2>부분 포함 insert</h2>
<div><footer>
footer 자리 입니다.
</footer></div>
💡 예시
<h2>부분 포함 : replace</h2>
<div th:replace="~{template/fragment/footer :: copy}"></div>
</script>
👍 결과(페이지 소스보기)
<h2>부분 포함 : replace</h2>
<footer>
footer 자리 입니다.
</footer>
💡 예시
<h2>부분 포함 단순 표현식</h2>
<div th:replace="template/fragment/footer :: copy"></div>
👍 결과(페이지 소스보기)
<h2>부분 포함 단순 표현식</h2>
<footer>
footer 자리 입니다.
</footer>
💡 예시
<h1>파라미터 사용</h1>
<div th:replace="~{template/fragment/footer :: copyParam('데이터1','데이터2')}">
</div>
👍 결과(페이지 소스보기)
<h1>파라미터 사용</h1>
<footer>
<p>파라미터 자리입니다.</p>
<p>데이터1</p>
<p>데이터2</p>
</footer>
👍 결과