본문 바로가기

스프링

[Thymeleaf] 텍스트, spring EL, 객체, URL 링크, 리터럴

text, utext

th:text는 태그 안의 텍스트를 전달 받은 값으로 표현하고자 할 때 사용한다.

th:utext는 unescape text로 태그 안의 텍스트 값에 html 태그 값이 있다면 이를 반영하고자 할 때 사용한다.

<label>
    <p class="label-txt" th:text="'이름은 ' + ${person.name} + '입니다.'"></p>
    <p class="label-txt" th:text="|나이는 ${person.age}입니다.|"></p>
    <p class="label-txt" th:utext="|학과는 <b>${person.department}</b>입니다.|"></p>
    <p class="label-txt" th:utext="|전공은 <b>${person.major}</b>입니다.|"></p>
</label>
  • 첫 번째 라인은 각 문자열들과 ${}이라는 변수 표현식을 더하여 문장을 출력한다.
  • 두 번째 라인은 각각 더하는 부분을 편리하게 하기 위해 ||이라는 Literal 표현식을 사용하여 문장을 출력한다.
  • 세 번째 라인과 네 번째 라인은 utext를 활용하여 <b>태그를 활용하여 문장을 출력한다.

Spring EL

TestData

Person testObject = new Person("GilSSang", 25, "컴공", "백앤드");
List<Person> testList = new ArrayList<>(Arrays.asList(testObject));
Map<String, Person> testMap = new HashMap<>();
testMap.put("Gil", testObject);

model.addAttribute("testObject", testObject);
model.addAttribute("testList", testList);
model.addAttribute("testMap", testMap);
  • testObject는 이전과 같이 Person 객체로 구성하였다.
  • testList에는 Person 객체를 담는 리스트로 구성하였다.
  • testMap에는 String을 Key로 Person을 Value로 하는 HashMap으로 구성하였다.

Object

<label>
    <p><b>Object</b></p>
    <p class="label-txt" th:text="|이름은 ${testObject.name}입니다.|"></p>
    <p class="label-txt" th:text="|나이는 ${testObject.getAge()}입니다.|"></p>
    <p class="label-txt" th:text="|학과는 ${testObject['department']}입니다.|"></p>
    <p class="label-txt" th:text="|전공은 ${testObject.major}입니다.|"></p>
</label>
  • 단순히 변수명으로 접근할 수 있다.
  • 프로퍼티 접근법으로 접근할 수 있다.
  • 슬라이싱 접근으로 접근할 수 있다.

List

<label>
    <p><b>List</b></p>
    <p class="label-txt" th:text="${testList[0].name}"></p>
    <p class="label-txt" th:text="${testList[0].getAge()}"></p>
    <p class="label-txt" th:text="${testList[0]['department']}"></p>
</label>
  • 원하는 인덱스로 인덱싱하여 해당 데이터에 접근할 수 있다.
  • 나머지는 Object 접근법과 동일하다.

Map

<label>
    <p><b>Map</b></p>
    <p class="label-txt" th:text="${testMap['Gil'].name}"></p>
    <p class="label-txt" th:text="${testMap['Gil'].getAge()}"></p>
    <p class="label-txt" th:text="${testMap['Gil']['department']}"></p>
</label>
  • 원하는 Key로 슬라이싱하여 해당 데이터에 접근할 수 있다.
  • 나머지는 Object 접근법과 동일하다.

기본 객체

  • ${#request}
  • ${#response}
  • ${#session}
  • ${#servletContext}
  • ${#locale}

편의 객체

  • ${param.파라미터명}
  • ${session.세션명}
  • ${@빈이름.빈메소드(빈파라미터)}

유틸리티 객체

URL 링크

경로 추가

model.addAttribute("link", "home");
  • 어떤 경로를 갈 지에 대한 정보를 모델에 저장한다.

URL 링크

<button type="submit" th:onclick="|location.href='@{/home}'|">버튼1</button>
<button type="submit" th:onclick="|location.href='@{/home(link=${link})}'|">버튼2</button>
<button type="submit" th:onclick="|location.href='@{/{link}(link=${link})}'|">버튼3</button>
<button type="submit" th:onclick="|location.href='@{/{link1}(link1=${link}, link=${link})}'|">버튼4</button>
  • @{}라는 URL 링크 표현식을 통해 해당 URL로 이동한다.
  • 첫 번째 라인은 직접 URL 링크를 입력해준다.
  • 두 번째 라인은 해당 URL 링크에 파라미터 값을 넣어준다.
  • 세 번째 라인은 URL 링크를 파라미터로 받아 이를 넣어준다.
  • 네 번째 라인은 2, 3을 혼합하여 진행한다.

리터럴

먼저, 리터럴에 해당하는 것들을 살펴보자.

  • 문자
  • 숫자
  • Boolean
  • Null

이것들을 사용하기 위해서는 항상 ' '로 묶어줘야 한다.

<p class="label-txt" th:text="'테스트'"></p>
<p class="label-txt" th:text="'0'"></p>
<p class="label-txt" th:text="'true'"></p>
<p class="label-txt" th:text="'null'"></p>

그렇지만, 리터럴들이 한 문장으로 이어지는 경우 ' '을 생략할 수 있다.

<p class="label-txt" th:text="리터럴테스트를1번하는중입니다.true.null"></p>

하지만 공백이 있을 경우에는 하나의 토큰으로 인식하지 못해 오류가 발생한다.

그에 따라, ' '를 붙여줘야 한다.

<p class="label-txt" th:text="'리터럴 테스트를 1번 하는 중입니다. true null'"></p>

추가적으로 변수가 존재한다면 +를 이용하여 이어줘야 한다.

<p class="label-txt" th:text="'이름? ' + ${testObject.getName()}"></p>

이를 간편하기 위해 리터럴식인 ||가 존재한다.

<p class="label-txt" th:text="|이름? ${testObject.getName()}|"></p>

참고문헌

https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html
https://www.inflearn.com/course/스프링-mvc-2/dashboard

'스프링' 카테고리의 다른 글

[Thymeleaf] 반복, 조건, 블럭  (0) 2021.09.22
[Thymeleaf] 연산, 속성값  (0) 2021.09.22
@RequestBody, @ResponseBody  (0) 2021.09.21
@ModelAttribute  (0) 2021.09.20
@RequestParam  (0) 2021.09.20