검색결과 리스트
글
스프링 MVC 2편 - 백엔드 웹 개발 활용 기술 1
인프런 강의 40일차.
- 스프링 MVC 2편 - 백엔드 웹 개발 활용 기술 1 (김영한 강사님)
- 1편에서 배운 MVC를 활용할 수 있는 기술 습득
- 타입 컨버터, 파일 업로드, 활용, 쿠키, 세션, 필터, 인터셉터, 예외 처리, 타임리프, 메시지, 국제화, 검증 등등
1. 타임 리프 기본기능
1.1 프로젝트 생성
- 프로젝트 선택 Project : Gradle Project
- Language : Java
- Spring Boot : 2.7.0
- Group : hello
- Artifact : thymeleaf-basic
- Name : thymeleaf-basic
- Package name : hello.thymeleaf
- Packaging : Jar
- Java : 11
- Dependencies : Spring Web, Thymeleaf, Lombok
1.2 타임리프 소개
- 공식 사이트 : https://www.thymeleaf.org
- 공식 메뉴얼 기본 기능 : https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
- 공식 메뉴얼 스프링 통합 : https://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html
- 타임리프 특징
> 서버 사이드 HTML 렌더링 (SSR)
> 네츄럴 템플릿
> 스프링 통합 지원
- 서버 사이드 HTML 렌더링 (SSR)
> 타임리프는 백엔드 서버에서 HTML을 동적으로 렌더링 하는 용도로 사용된다.
- 네츄럴 템플릿
> 타임리프는 순수 HTML을 최대한 유지하는 특징이 있다. 타임리프로 작성한 파일은 HTML을 유지하기 때문에 웹 브라우저에서 파일을 직접 열어도 내용을 확인할 수 있고, 서버를 통해 뷰 템플릿을 거치면 동적으로 변경된 결과를 확인할 수 있다.
> JSP를 포함한 다른 뷰 템플릿들은 해당 파일을 열면, JSP 파일 자체를 그대로 웹 브라우저에서 열어보면 JSP 소스코드와 HTML이 뒤죽박죽 섞여서 웹 브라우저에서 정상적인 HTML 결과를 확인할 수 없다. 오직 서버를 통해서 JSP가 렌더링 되고 HTML 응답 결과를 받아야 화면을 확인할 수 있다.
> 반면에 타임리프로 작성된 파일은 해당 파일을 그대로 웹 브라우저에서 열어도 정상적인 HTML 결과를 확인할 수 있다. 물론 이 경우 동적으로 결과가 렌더링 되지는 않는다. 하지만 HTML 마크업 결과가 어떻게 되는지 파일만 열어도 바로 확인할 수 있다.
> 이렇게 순수 HTML을 그대로 유지하면서 뷰 템플릿도 사용할 수 있는 타임리프의 특징을 네츄럴 템플릿 (natural templates)이라 한다
- 스프링 통합 지원
> 타임리프는 스프링과 자연스럽게 통합되고, 스프링의 다양한 기능을 편리하게 사용할 수 있게 지원한다.
- 타임리프 사용 선언
<html xmlns:th="http://www.thymeleaf.org">
- 기본 표현식
> 다음과 같은 기본 표현식들을 제공한다.
• 간단한 표현:
◦ 변수 표현식: ${...}
◦ 선택 변수 표현식: *{...}
◦ 메시지 표현식: #{...}
◦ 링크 URL 표현식: @{...}
◦ 조각 표현식: ~{...}
• 리터럴
◦ 텍스트: 'one text', 'Another one!',…
◦ 숫자: 0, 34, 3.0, 12.3,…
◦ 불린: true, false
◦ 널: null
◦ 리터럴 토큰: one, sometext, main,…
• 문자 연산:
◦ 문자 합치기: +
◦ 리터럴 대체: |The name is ${name}|
• 산술 연산:
◦ Binary operators: +, -, *, /, %
◦ Minus sign (unary operator): -
• 불린 연산:
◦ Binary operators: and, or
◦ Boolean negation (unary operator): !, not
• 비교와 동등:
◦ 비교: >, <, >=, <= (gt, lt, ge, le)
◦ 동등 연산: ==, != (eq, ne)
• 조건 연산:
◦ If-then: (if) ? (then)
◦ If-then-else: (if) ? (then) : (else)
◦ Default: (value) ?: (defaultvalue)
• 특별한 토큰:
◦ No-Operation: _
1.3 텍스트 - text, utext
- 타임리프는 기본적으로 HTML 태그의 속성에 기능을 정의해서 동작한다.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>컨텐츠에 데이터 출력하기</h1>
<ul>
<!-- HTML의 콘텐츠(content)에 데이터를 출력할 때는 th:text 를 사용하면 된다. -->
<li>th:text 사용 <span th:text="${data}"></span></li>
<!-- HTML 콘텐츠 영역안에서 직접 데이터를 출력하고 싶으면 [[...]] 를 사용하면 된다. -->
<li>컨텐츠 안에서 직접 출력하기 = [[${data}]]</li>
</ul>
</body>
</html>
* Escape
- HTML 문서는 < , > 같은 특수 문자를 기반으로 정의된다. 따라서 뷰 템플릿으로 HTML 화면을 생성할 때는 출력하는 데이터에 특수 문자가 있는 것을 주의해서 사용해야 한다.
- 변경 전 : "Hello Spring!"
- 변경 후 : "Hello <b>Spring!</b>
- b 태그를 사용해서 Spring!이라는 단어가 진하게 나오도록 해보자.
- 웹 브라우저 실행 결과 : Hello <b>Spring!</b>, 소스보기: Hello <b>Spring!</b>
> 개발자가 의도한 결과는 <b> 태그를 이용해 강조하는 것이 목적이었지만, 해당 태그가 렌더링되지않고 그대로 출력됨
* HTML 엔티티
- 웹 브라우저는 < 를 HTML 태그의 시작으로 인식한다. 따라서 < 를 태그의 시작이 아니라 문자로 표현할 수 있는 방법이 필요한데, 이것을 HTML 엔티티라 한다.
- HTML에서 사용하는 특수 문자를 HTML 엔티티로 변경하는 것을 이스케이프(escape)라 한다.
- 타임리프가 제공하는 th:text , [[...]] 는 기본적으로 이스케이스(escape)를 제공한다
* Unescape
th:text -> th:utext
[[...]] -> [(...)]
- 타임리프에서 이스케이프 기능을 사용하지 않으려면 위와 같이 사용하면 된다.
package hello.thymeleaf.basic;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/basic")
public class BasicController {
@GetMapping("text-basic")
public String textBasic(Model model){
model.addAttribute("data", "Hello Spring");
return "basic/text-basic";
}
@GetMapping("/text-unescaped")
public String textUnescaped(Model model) {
model.addAttribute("data", "Hello <b>Spring!</b>");
return "basic/text-unescaped";
}
}
- hello.thymeleaf.basic.BasicController.java
- 기존 호출 및 unescaped 구현
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<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>
</html>
- resources.templates.basic.text-unescaped.html
- th:inline="none" : 타임리프는 [[...]] 를 해석하기 때문에, 화면에 [[...]] 글자를 보여줄 수 없다. 이 태그 안에서는 타임리프가 해석하지 말라는 옵션이다.
text vs utext
- th:text = Hello <b>Spring!</b>
- th:utext = Hello Spring!
[[...]] vs [(...)]
- [[...]] = Hello <b>Spring!</b>
- [(...)] = Hello Spring!
* 실제 서비스를 개발하다 보면 escape를 사용하지 않아서 HTML이 정상 렌더링 되지 않는 수 많은 문제가 발생한다. escape를 기본으로 하고, 꼭 필요한 때만 unescape를 사용하자.
* 변수 - SpringEL
- 타임리프에서 변수를 사용할 때는 변수 표현식을 사용한다
- 변수 표현식에는 스프링 EL이라는 스프링이 제공하는 표현식을 사용할 수 있다.
변수 표현식 : ${...}
@GetMapping("/variable")
public String variable(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";
}
@Data
static class User {
private String username;
private int age;
public User(String username, int age) {
this.username = username;
this.age = age;
}
}
- hello.thymeleaf.basic.BasicController.java
- 변수표현식 구현
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>SpringEL 표현식</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>
</body>
</html>
- resources.templates.basic.variable.html
- SpringEL로 다양한 표현식 사용
SpringEL 표현식
- ${user.username} = userA // user의 username을 프로퍼티 접근법으로 표현 = user.getUsername()
- ${user['username']} = userA // 위와 동일
- ${user.getUsername()} = userA // user의 getUsername() 을 직접 호출
- ${users[0].username} = userA // List의 첫 번째 회원 username 프로퍼티 접근 = list.get(0).getUsername()
- ${users[0]['username']} = userA // 위와 같음
- ${users[0].getUsername()} = userA // List에서 첫 번째 회원을 찾고 메서드 직접 호출
- ${userMap['userA'].username} = userA // Map에서 userA의 username프로퍼티접근 = map.get("userA").getUsername()
- ${userMap['userA']['username']} = userA // 위와 같음
- ${userMap['userA'].getUsername()} = userA // Map에서 userA를 찾고 메서드 직접 호출
* 지역 변수 선언
<h1>지역 변수 - (th:with)</h1>
<div th:with="first=${users[0]}">
<p>처음 사람의 이름은 <span th:text="${first.username}"></span></p>
</div>
- th:with 를 사용하면 지역 변수를 선언해서 사용할 수 있다. 지역 변수는 선언한 태그 안에서만 사용할 수 있다
1.4 기본객체들
- 타임리프는 기본 객체들을 제공한다.
- ${#request}, ${#response}, ${#session}, ${#servletContext}, ${#locale}
- 그런데 #request 는 HttpServletRequest 객체가 그대로 제공되기 때문에 데이터를 조회하려면 request.getParameter("data") 처럼 불편하게 접근해야 한다.
- 이를 해결하기 위해 편의 객체도 제공한다.
HTTP 요청 파라미터 접근 : param
예) ${param.paramData}
HTTP 세션 접근 : session
예) ${session.sessionData}
스프링 빈 접근 : @
예) ${@helloBean.hello('Spring!')}
@GetMapping("/basic-objects")
public String basicObjects(HttpSession session) {
session.setAttribute("sessionData", "Hello Session");
return "basic/basic-objects";
}
@Component("helloBean")
static class HelloBean {
public String hello(String data) {
return "Hello " + data;
}
}
- hello.thymeleaf.basic.BasicController.java
- ComponentScan에 의해 helloBean객체가 스프링 빈에 등록됨
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>식 기본 객체 (Expression Basic Objects)</h1>
<ul>
<li>request = <span th:text="${#request}"></span></li>
<li>response = <span th:text="${#response}"></span></li>
<li>session = <span th:text="${#session}"></span></li>
<li>servletContext = <span th:text="${#servletContext}"></span></li>
<li>locale = <span th:text="${#locale}"></span></li>
</ul>
<h1>편의 객체</h1>
<ul>
<li>Request Parameter = <span th:text="${param.paramData}"></span></li>
<li>session = <span th:text="${session.sessionData}"></span></li>
<li>spring bean = <span th:text="${@helloBean.hello('Spring!')}"></span></li>
</ul>
</body>
</html>
- resources.templates.basic.basic-objects.html
- 타임리프 기본 객체 사용 html
식 기본 객체 (Expression Basic Objects)
- request = org.apache.catalina.connector.RequestFacade@134e88de
- response = org.apache.catalina.connector.ResponseFacade@4588eb74
- session = org.apache.catalina.session.StandardSessionFacade@6cfcee76
- servletContext = org.apache.catalina.core.ApplicationContextFacade@6970520c
- locale = ko_KR
* httpServletRequest객체를 구현해놓은 것 = 톰캣에서 사용 시 Facede가 기본으로 들어옴
편의 객체
- Request Parameter = HelloParam
- session = Hello Session
- spring bean = Hello Spring!
1.5 유틸리티 객체
- 타임리프는 문자, 숫자, 날짜, URI등을 편리하게 다루는 다양한 유틸리티 객체들을 제공한다
- #message : 메시지, 국제화 처리
- #uris : URI 이스케이프 지원
- #dates : java.util.Date 서식 지원
- #calendars : java.util.Calendar 서식 지원
- #temporals : 자바8 날짜 서식 지원
- #numbers : 숫자 서식 지원
- #strings : 문자 관련 편의 기능
- #objects : 객체 관련 기능 제공
- #bools : boolean 관련 기능 제공
- #arrays : 배열 관련 기능 제공
- #lists, #sets, #maps : 컬렉션 관련 기능 제공
- #ids : 아이디 처리 관련 기능 제공, 뒤에서 설명
* 타임리프 유틸리티 객체 : https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#expression-utilityobjects
* 유틸리티 객체 예시 : https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-b-expressionutility-objects
1.6 자바8 날짜
- 타임리프에서 자바8 날짜인 LocalDate, LocalDateTime, Instant 를 사용하려면 추가 라이브러리가 필요하다.
- 스프링 부트 타임리프를 사용하면 해당 라이브러리가 자동으로 추가되고 통합된다.
* 타임리프 자바8 날짜 지원 라이브러리 : thymeleaf-extras-java8time
* 자바8 날짜용 유틸리티 객체 : #temporals
<span th:text="${#temporals.format(localDateTime, 'yyyy-MM-dd HH:mm:ss')}"></span>
@GetMapping("/date")
public String date(Model model) {
model.addAttribute("localDateTime", LocalDateTime.now());
return "basic/date";
}
- hello.thymeleaf.basic.BasicController.java
- 타임리프 LocalDateTIme 처리 메소드
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<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>
</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>
</html>
- resources.templates.basic.date.html
- 타임리프 date 사용 html
LocalDateTime
- default = 2022-05-31T21:20:30.118461200
- yyyy-MM-dd HH:mm:ss = 2022-05-31 21:20:30
LocalDateTime - Utils
- ${#temporals.day(localDateTime)} = 31
- ${#temporals.month(localDateTime)} = 5
- ${#temporals.monthName(localDateTime)} = 5월
- ${#temporals.monthNameShort(localDateTime)} = 5월
- ${#temporals.year(localDateTime)} = 2022
- ${#temporals.dayOfWeek(localDateTime)} = 2
- ${#temporals.dayOfWeekName(localDateTime)} = 화요일
- ${#temporals.dayOfWeekNameShort(localDateTime)} = 화
- ${#temporals.hour(localDateTime)} = 21
- ${#temporals.minute(localDateTime)} = 20
- ${#temporals.second(localDateTime)} = 30
- ${#temporals.nanosecond(localDateTime)} = 118461200
'Spring 정리' 카테고리의 다른 글
스프링 MVC 2편 - 백엔드 웹 개발 활용 기술 3 (0) | 2022.06.03 |
---|---|
스프링 MVC 2편 - 백엔드 웹 개발 활용 기술 2 (0) | 2022.05.31 |
스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술 28 (1) | 2022.05.29 |
스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술 27 (0) | 2022.05.29 |
스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술 26 (0) | 2022.05.27 |