김영한의 스프링 완전 정복 로드맵
스프링 MVC 2편 - 백엔드 웹 개발 활용 기술
섹션1~섹션3 정리입니다.
타임리프는 백엔드 서버에서 HTML을 동적으로 렌더링 하는 용도로 사용
타임리프는 스프링과 자연스럽게 통합되고, 스프링의 다양한 기능을 편리하게 사용할 수 있게 지원 한다
타임리프를 사용하려면 다음 선언을 하면 됨
<html xmlns:th="http://www.thymeleaf.org">
간단한 표현
리터럴
문자 연산
산술 연산
불린 연산
비교와 동등
조건 연산
특별한 토큰:
th:text
를 사용<span th:text="${data}">
[[...]]
를 사용하면 된다컨텐츠 안에서 직접 출력하기 = [[${data}]]
HTML 문서는 <
, >
같은 특수 문자를 기반으로 정의, 따라서 뷰 템플릿으로 HTML 화면을 생성할 때는 출력하는 데이터에 이러한 특수 문자가 있는 것을 주의해서 사용해야 한다
<
를 HTML 테그의 시작으로 인식한다<
를 테그의 시작이 아니라 문자로 표현할 수있는 방법이 필요th:text
, [[...]]
는 기본적으로 이스케이스(escape)를 제공한다.변수 표현식 : ${...}
th:with 를 사용하면 지역 변수를 선언해서 사용 가능
지역 변수는 선언한 테그 안에서만 사용
<h1>지역 변수 - (th:with)</h1>
<div th:with="first=${users[0]}">
<p>처음 사람의 이름은 <span th:text="${first.username}"></span></p>
</div>
타임리프는 기본 객체들을 제공
${#request}
- 스프링 부트 3.0부터 제공하지 않음X${#response}
- 스프링 부트 3.0부터 제공하지 않음X${#session}
- 스프링 부트 3.0부터 제공하지 않음X${#servletContext}
- 스프링 부트 3.0부터 제공하지 않음X${#locale}
타임리프는 문자, 숫자, 날짜, URI등을 편리하게 다루는 다양한 유틸리티 객체들을 제공
#message
: 메시지, 국제화 처리#uris
: URI 이스케이프 지원#dates
: java.util.Date 서식 지원#calendars
: java.util.Calendar 서식 지원#temporals
: 자바8 날짜 서식 지원#numbers
: 숫자 서식 지원#strings
: 문자 관련 편의 기능#objects
: 객체 관련 기능 제공#bools
: boolean 관련 기능 제공#arrays
: 배열 관련 기능 제공#lists
, #sets
, #maps
: 컬렉션 관련 기능 제공#ids
: 아이디 처리 관련 기능 제공, 뒤에서 설명thymeleaf-extras-java8time
#temporals
<span th:text="${#temporals.format(localDateTime, 'yyyy-MM-dd HH:mm:ss')}"></span>
타임리프에서 URL을 생성할 때는 @{...}
문법을 사용
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>URL 링크</h1>
<ul>
<li><a th:href="@{/hello}">basic url</a></li>
<li><a th:href="@{/hello(param1=${param1}, param2=${param2})}">hello query param</a></li>
<li><a th:href="@{/hello/{param1}/{param2}(param1=${param1}, param2=${param2})}">path variable</a></li>
<li><a th:href="@{/hello/{param1}(param1=${param1}, param2=${param2})}">path variable + query parameter</a></li>
</ul>
</body>
</html>
@{/hello}
→ /hello
@{/hello(param1=${param1}, param2=${param2})}
/hello?param1=data1¶m2=data2
@{/hello/{param1}/{param2}(param1=${param1}, param2=${param2})}
/hello/data1/data2
@{/hello/{param1}(param1=${param1}, param2=${param2})}
/hello/data1?param2=data2
/hello
: 절대 경로hello
: 상대 경로리터럴은 소스 코드상에 고정된 값을 말하는 용어 -> 문자, 숫자, null, 불린 리터럴이 존재.
<span th:text="'hello'">
<span th:text="hello">
<span th:text="hello world!"></span>
<span th:text="'hello world!'"></span>
>
(gt), <
(lt), >=
(ge), <=
(le), !
(not), ==
(eq), !=
(neq, ne)th:*
속성을 지정하는 방식으로 동작<input type="text" name="mock" th:name="userA" />
→ 타임리프 렌더링 후 <input type="text" name="userA" />
th:attrappend
: 속성 값의 뒤에 값을 추가한다.
th:attrprepend
: 속성 값의 앞에 값을 추가한다.
th:classappend
: class 속성에 자연스럽게 추가한다.
HTML에서 checked 속성은 checked 속성의 값과 상관없이 checked라는 속성만 있어도 체크가 된다
이런 부분이 true , false 값을 주로 사용하는 개발자 입장에서는 불편,
타임리프의 th:checked
는 값이 false 인 경우 checked 속성 자체를 제거한다
<input type="checkbox" name="active" th:checked="false" />
→ 타임리프 렌더링 후: <input type="checkbox" name="active" />
<tr th:each="user, userStat : ${users}">
<td th:text="${userStat.count}">username</td>
<td th:text="${user.username}">username</td>
<td th:text="${user.age}">0</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>
current = <span th:text="${userStat.current}"></span>
</td>
</tr>
${users}
)의 값을 하나씩 꺼내서 왼쪽 변수(user
)에 담아서 태그를 반복 실행false
인 경우 <span>...<span>
부분 자체가 렌더링 되지 않고 사라진다<span th:text="'미성년자'" th:if="${user.age lt 20}"></span>
<td th:switch="${user.age}">
<span th:case="10">10살</span>
<span th:case="20">20살</span>
<span th:case="*">기타</span>
</td>
*
은 만족하는 조건이 없을 때 사용하는 디폴트이다
<h1>1. 표준 HTML 주석</h1>
<!--
<span th:text="${data}">html data</span>
-->
자바스크립트의 표준 HTML 주석은 타임리프가 렌더링 하지 않고, 그대로 남겨둔다.
<h1>2. 타임리프 파서 주석</h1>
<!--/* [[${data}]] */-->
<!--/*-->
<span th:text="${data}">html data</span>
<!--*/-->
타임리프 파서 주석은 타임리프의 진짜 주석, 렌더링에서 주석 부분을 제거한다
<h1>3. 타임리프 프로토타입 주석</h1>
<!--/*/
<span th:text="${data}">html data</span>
/*/-->
타임리프 프로토타입은 약간 특이한데, HTML 주석에 약간의 구문을 더했다
HTML 파일을 웹 브라우저에서 그대로 열어보면 HTML 주석이기 때문에 렌더링하지 않고 주석처리 되지만, 타임리프 렌더링을 거치면 이 부분이 정상 렌더링 된다
<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>
타임리프의 특성상 HTML 태그안에 속성으로 기능을 정의해서 사용하는데, 위 예처럼 이렇게 사용하기 애매한 경우에 사용하면 된다
<th:block>
은 렌더링시 제거된다
자바스크립트에서 타임리프를 편리하게 사용할 수 있는 자바스크립트 인라인 기능을 제공
<script th:inline="javascript">
<!-- 자바스크립트 인라인 사용 후 -->
<script th:inline="javascript">
var username = [[${user.username}]];
var age = [[${user.age}]];
//자바스크립트 내추럴 템플릿
var username2 = /*[[${user.username}]]*/ "test username";
//객체
var user = [[${user}]];
</script>
var username = [[${user.username}]];
var username = userA;
var username = "userA";
"
→ \"
타임리프는 HTML 파일을 직접 열어도 동작하는 내추럴 템플릿 기능을 제공
var username2 = /*[[${user.username}]]*/ "test username";
var username2 = /*userA*/ "test username";
var username2 = "userA";
📌 인라인 사용 전 결과를 보면 정말 순수하게 그대로 해석, 내추럴 템플릿 기능이 동작X
타임리프의 자바스크립트 인라인 기능을 사용하면 객체를 JSON으로 자동으로 변환
var user = [[${user}]];
var user = BasicController.User(username=userA, age=10);
var user = {"username":"userA","age":10};
<script th:inline="javascript">
[# th:each="user, stat : ${users}"]
var user[[${stat.count}]] = [[${user}]];
[/]
</script>
[/]
: 자바;
세미콜론 처럼 타임리프가 끝난다는 뜻 웹 페이지를 개발할 때는 공통 영역이 많이 있다 예를 들어서 상단 영역이나 하단 영역, 좌측 카테고리 등등 여러 페이지에서 함께 사용하는 영역들이 있다
이런 부분을 코드를 복사해서 사용한다면 변경시 여러 페이지를 다 수정해야 하므로 상당히 비효율 적이다
그래서 타임리프는 이런 문제를 해결하기 위해 템플릿 조각과 레이아웃 기능을 지원한다
/resources/templates/template/fragment/footer.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<footer th:fragment="copy">
푸터 자리 입니다.
</footer>
<footer th:fragment="copyParam (param1, param2)">
<p>파라미터 자리 입니다.</p>
<p th:text="${param1}"></p>
<p th:text="${param2}"></p>
</footer>
</body>
</html>
th:fragment
가 있는 태그는 다른곳에 포함되는 코드 조각으로 이해/resources/templates/template/fragment/fragmentMain.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>부분 포함</h1>
<h2>부분 포함 insert</h2>
<div th:insert="~{template/fragment/footer :: copy}"></div>
<h2>부분 포함 replace</h2>
<div th:replace="~{template/fragment/footer :: copy}"></div>
<h2>부분 포함 단순 표현식</h2>
<div th:replace="template/fragment/footer :: copy"></div>
<h1>파라미터 사용</h1>
<div th:replace="~{template/fragment/footer :: copyParam ('데이터1', '데이터
2')}"></div>
</body>
</html>
template/fragment/footer :: copy
: template/fragment/footer.html
템플릿에 있는 th:fragment="copy"
라는 부분을 템플릿 조각으로 가져와서 사용한다는 의미<div th:insert="~{template/fragment/footer :: copy}"></div>
th:insert
를 사용하면 현재 태그(div
) 내부에 추가<div th:replace="~{template/fragment/footer :: copy}"></div>
th:replace
를 사용하면 현재 태그(div
)를 대체다음과 같이 파라미터를 전달해서 동적으로 조각을 렌더링 할 수 있음
<div th:replace="~{template/fragment/footer :: copyParam ('데이터1', '데이터2')}"></div>
<footer th:fragment="copyParam (param1, param2)">
<p>파라미터 자리 입니다.</p>
<p th:text="${param1}"></p>
<p th:text="${param2}"></p>
</footer>
코드 조각을 레이아웃에 넘겨서 사용하는 방법
예를 들어서 <head>
에 공통으로 사용하는 css , javascript 같은 정보들이 있는데, 이러한 공통 정보들을 한 곳에 모아두고, 공통으로 사용하지만, 각 페이지마다 필요한 정보를 더 추가해서 사용하고 싶다면 다음과 같이 사용하면 된다
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="common_header(title,links)">
<title th:replace="${title}">레이아웃 타이틀</title>
<!-- 공통 -->
<link rel="stylesheet" type="text/css" media="all" th:href="@{/css/awesomeapp.css}">
<link rel="shortcut icon" th:href="@{/images/favicon.ico}">
<script type="text/javascript" th:src="@{/sh/scripts/codebase.js}"></script>
<!-- 추가 -->
<th:block th:replace="${links}" />
</head>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="template/layout/base :: common_header(~{::title},~{::link})">
<title>메인 타이틀</title>
<link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
<link rel="stylesheet" th:href="@{/themes/smoothness/jquery-ui.css}">
</head>
<body>
메인 컨텐츠
</body>
</html>
common_header(~{::title},~{::link})
이 부분이 핵심::title
은 현재 페이지의 title 태그들을 전달::link
는 현재 페이지의 link 태그들을 전달앞서 이야기한 개념을 <head>
정도에만 적용하는게 아니라 <html>
전체에 적용 가능
<!DOCTYPE html>
<html th:fragment="layout (title, content)" xmlns:th="http://www.thymeleaf.org">
<head>
<title th:replace="${title}">레이아웃 타이틀</title>
</head>
<body>
<h1>레이아웃 H1</h1>
<div th:replace="${content}">
<p>레이아웃 컨텐츠</p>
</div>
<footer>
레이아웃 푸터
</footer>
</body>
</html>
layoutFile.html
을 보면 기본 레이아웃을 가지고 있는데, <html>
에 th:fragment
속성이 정의되어 있다<!DOCTYPE html>
<html th:replace="~{template/layoutExtend/layoutFile :: layout(~{::title}, ~{::section})}"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>메인 페이지 타이틀</title>
</head>
<body>
<section>
<p>메인 페이지 컨텐츠</p>
<div>메인 페이지 포함 내용</div>
</section>
</body>
</html>
layoutExtendMain.html
는 현재 페이지인데, <html>
자체를 th:replace
를 사용해서 변경하는 것을 확인할 수 있음layoutFile.html
에 필요한 내용을 전달하면서 <html>
자체를 layoutFile.html
로 변경<!DOCTYPE html>
<html>
<head>
<title>메인 페이지 타이틀</title>
</head>
<body>
<h1>레이아웃 H1</h1>
<section>
<p>메인 페이지 컨텐츠</p>
<div>메인 페이지 포함 내용</div>
</section>
<footer>
레이아웃 푸터
</footer>
</body>
</html>
${@myBean.doSomething()}
처럼 스프링 빈 호출 지원th:object
(기능 강화, 폼 커맨드 객체 선택)th:field
, th:errors
, th:errorclass
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
application.properties
에서 변경가능 (링크 참고)th:object
: 커맨드 객체를 지정한다 *{...}
: 선택 변수 식th:object
에서 선택한 객체에 접근한다th:field
: HTML 태그의 id , name , value 속성을 자동으로 처리요구사항 추가
<div>판매 여부</div>
<div>
<div class="form-check">
<input type="checkbox" id="open" name="open" class="form-check-input">
<label for="open" class="form-check-label">판매 오픈</label>
</div>
</div>
FormItemController : item.open=true //체크 박스를 선택하는 경우
FormItemController : item.open=null //체크 박스를 선택하지 않는 경우
open=on
이라는 값이 넘어가고, 스프링은 on
이라는 문자를 true
타입으로 변환해준다open
이라는 필드 자체가 서버로 전송되지 않는다<input type="checkbox" id="open" name="open" class="form-check-input">
<input type="hidden" name="_open" value="on"/> <!-- 히든 필드 추가 -->
📌이런 문제를 해결하기 위해서 스프링 MVC는 히든 필드를 하나 만들어서,_open
처럼 기존 체크 박스 이름 앞에 언더스코어( _ )를 붙여서 전송하면 체크를 해제했다고 인식할 수 있다
open
은 전송되지 않고, _open
만 전송되는데, 이 경우 스프링 MVC는 체크를 해제했다고 판단한다<div>판매 여부</div>
<div>
<div class="form-check">
<input type="checkbox" id="open" th:field="*{open}" class="form-check-input">
<label for="open" class="form-check-label">판매 오픈</label>
</div>
</div>
th:field
를 사용하면 타임리프가 자동으로 히든필드를 생성해준다@ModelAttribute("regions")
public Map<String, String> regions() {
Map<String, String> regions = new LinkedHashMap<>();
regions.put("SEOUL", "서울");
regions.put("BUSAN", "부산");
regions.put("JEJU", "제주");
return regions;
}
등록 폼, 상세화면, 수정 폼에서 모두 서울, 부산, 제주라는 체크 박스를 반복해서 보여주어야 하는데, 이를 위해 각각의 컨트롤러에서 model.addAttribute(...)
을 사용해서 체크 박스를 구성하는 데이터를 반복해서 넣어주어야 한다
@ModelAttribute
는 이렇게 컨트롤러에 있는 별도의 메서드에 적용할 수 있다
반환한 값이 자동으로 모델(model)
에 담기게 된다
각각의 컨트롤러 메서드에서 모델에 직접 데이터를 담아서 처리하는 것도 가능
<div>등록 지역</div>
<div th:each="region : ${regions}" class="form-check form-check-inline">
<input type="checkbox" th:field="*{regions}" th:value="${region.key}"
class="form-check-input">
<label th:for="${#ids.prev('regions')}"
th:text="${region.value}" class="form-check-label">서울</label>
</div>
</div
th:for="${#ids.prev('regions')}"
멀티 체크박스는 같은 이름의 여러 체크박스를 만들 수 있다
그런데 문제는 이렇게 반복해서 HTML 태그를 생성할 때, 생성된 HTML 태그 속성에서name
은 같아도 되지만, id
는 모두 달라야 한다
따라서 타임리프는 체크박스를 each
루프 안에서 반복해서 만들 때 임의로 1
, 2
, 3
숫자를 뒤에 붙여준다
HTML의 id
가 타임리프에 의해 동적으로 만들어지기 때문에 <label for="id 값">
으로 label
의 대상이 되는 id
값을 임의로 지정하는 것은 곤란하다
타임리프는 ids.prev(...)
, ids.next(...)
을 제공해서 동적으로 생성되는 id
값을 사용할 수 있도록 한다
@ModelAttribute("itemTypes")
public ItemType[] itemTypes() {
return ItemType.values(); // ENUM의 모든 정보를 배열로 반환
}
<div>
<div>상품 종류</div>
<div th:each="type : ${itemTypes}" class="form-check form-check-inline">
<input type="radio" th:field="*{itemType}" th:value="${type.name()}"
class="form-check-input">
<label th:for="${#ids.prev('itemType')}" th:text="${type.description}"
class="form-check-label">
BOOK
</label>
</div>
</div>
<div>
<div>배송 방식</div>
<select th:field="*{deliveryCode}" class="form-select">
<option value="">==배송 방식 선택==</option>
<option th:each="deliveryCode : ${deliveryCodes}" th:value="${deliveryCode.code}"
th:text="${deliveryCode.displayName}">FAST</option>
</select>
</div>
<div>
<div>배송 방식</div>
<select th:field="${item.deliveryCode}" class="form-select" disabled>
<option value="">==배송 방식 선택==</option>
<option th:each="deliveryCode : ${deliveryCodes}" th:value="${deliveryCode.code}"
th:text="${deliveryCode.displayName}">FAST</option>
</select>
</div>
item.html
에는 th:object
를 사용하지 않았기 때문에 th:field
부분에 ${item.deliveryCode}
으로 적어주어야 한다*{deliveryCode}
= ${item.deliveryCode}
<div>
<DIV>배송 방식</DIV>
<select class="form-select" id="deliveryCode" name="deliveryCode">
<option value="">==배송 방식 선택==</option>
<option value="FAST" selected="selected">빠른 배송</option>
<option value="NORMAL">일반 배송</option>
<option value="SLOW">느린 배송</option>
</select>
</div>
메시지에서 설명한 메시지 파일(messages.properties)을 각 나라별로 별도로 관리하면 서비스를 국제화 할 수 있다
한국인지 영어에서 접근한 것인지는 인식 방법은 HTTP accept-language해더 값을 사용, 또는 사용자가 직접 언어를 선택하도록 하고 쿠키 등을 사용해서 처리하면 된다
스프링은 기본적인 메시지와 국제화 기능을 모두 제공 하며,타임리프도 스프링이 제공하는 메시지와 국제화 기능을 편리하게 통합해서 제공한다
메시지 관리 기능을 사용하려면 스프링이 제공하는 MessageSource를 스프링 빈으로 등록
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasenames("messages", "errors");
messageSource.setDefaultEncoding("utf-8");
return messageSource;
}
spring.messages.basename=messages
MessageSource
를 스프링 빈으로 등록하지 않고, 스프링 부트와 관련된 별도의 설정을 하지 않으면 messages
라는 이름으로 기본 등록된다 public interface MessageSource {
String getMessage(String code, @Nullable Object[] args, @Nullable String defaultMessage, Locale locale);
String getMessage(String code, @Nullable Object[] args, Locale locale) throws NoSuchMessageException;
messages.properties
hello=안녕
hello.name=안녕 {0}
@Test
void helloMessage() {
String result = ms.getMessage("hello", null, null);
assertThat(result).isEqualTo("안녕");
}
@Test
void notFoundMessageCode() {
assertThatThrownBy(() -> ms.getMessage("no_code", null, null))
.isInstanceOf(NoSuchMessageException.class);
}
@Test
void notFoundMessageCodeDefaultMessage() {
String result = ms.getMessage("no_code", null, "기본 메시지", null);
assertThat(result).isEqualTo("기본 메시지");
}
@Test
void argumentMessage() {
String result = ms.getMessage("hello.name", new Object[]{"Spring"}, null);
assertThat(result).isEqualTo("안녕 Spring");
}
@Test
void defaultLang() {
assertThat(ms.getMessage("hello", null, null)).isEqualTo("안녕");
assertThat(ms.getMessage("hello", null, Locale.KOREA)).isEqualTo("안녕");
}
@Test
void enLang() {
assertThat(ms.getMessage("hello", null,
Locale.ENGLISH)).isEqualTo("hello");
}
📌 보충
Locale 정보가 없는 경우 Locale.getDefault() 을 호출해서 시스템의 기본 로케일을 사용
예) locale = null인 경우 시스템 기본 locale이 ko_KR 이므로 messages_ko.properties 조회시도,
조회 실패 messages.properties 조회
messages.properties
label.item=상품
<div th:text="#{label.item}"></h2>
<div>상품</h2>
hello.name=안녕 {0}
<p th:text="#{hello.name(${item.itemName})}"></p>
public interface LocaleResolver {
Locale resolveLocale(HttpServletRequest request);
void setLocale(HttpServletRequest request, @Nullable HttpServletResponse response, @Nullable Locale locale);
}