on
[thymeleaf] 기본 기능 정리 - 01
[thymeleaf] 기본 기능 정리 - 01
반응형
01, 02, 03, 04에 걸쳐 thymeleaf를 간단히 정리하고자 한다. 인프런에서 영한님의 인프런 강의를 듣고 있는데 thymeleaf 부분을 강의하신 내용이 있었다.
강의 내에서 서버 개발자더라도 SSR thymeleaf 엔진을 아는 것이 좋다고 말씀하시고 MVC 강의 첫번째 부분이 thymeleaf 내용으로 진행되는데 블로그에 해당 내용을 정리해 보고자 한다.
더 자세한 사항과 내용은 인프런 강의를 듣는걸로,,
(Project 생성 및 thymeleaf 설정까지는 생략한다.)
1-1. 텍스트 - text
보통 JSP를 활용하여 서버에서 전달받은 변수값을 사용하기 위해서는 [[${message}]]"; 이런식의 변수선언을 해준다.
thymeleaf에서는 다양한 표현식을 통해 이를 나타낸수 있다.
밑의 코드에서 사용한 표현식은 변수 표현식으로 ${...} 형태로 나타난다.
@GetMapping("/text-basic") public String textBasic(Model model){ model.addAttribute("data","Hello ErJuer01"); return "mvc/text-basic"; }
컨텐츠에 데이터 출력하기 th:text 사용 컨텐츠 안에서 직접 출력하기 = [[${data}]]
화면 View 상태
html 소스코기
html 소스를 보면
부분이 Hello ErJuer01 로 data값이 적용된 것을 볼 수 있으며
[[${data}]] 또한 Hello ErJuer01 로 data값이 적용된것을 볼 수 있다.
1-2. Escape
HTML 문서에서 태그의 시작을 나타내는 '<'과 태그의 끝을 나타내는 '>'로 이루어져 있는데 태그가 아닌 View에서 '<' 기호를 사용하여 보여주는 경우도 있다. (공백 포함)
HTML에서는 < 같은 문자를 사용하여 나타내고 있는데 뷰 템플릿으로 HTML 생성 할 경우에도 주의하여 사용해야 한다.
@GetMapping("/text-unescaped") public String textUnescaped(Model model){ model.addAttribute("data","Hello ErJuer01!"); return "mvc/text-unescaped"; }
표현 방법은 두가지가 있다.
1. utext
2. [()]
th:text = th:utext = [[...]] = [[${data}]] [(...)] = [(${data})]
escape. 표시 비교
두가지의 표현식으로 태그를 활용하여 HTML에 나타 낼 수 있다.
2. 변수 - SpringEL
타임리프에서 변수를 사용할 때는 변수 표현식을 사용한다. : ${..}
@GetMapping("/variable") public String variable(Model model){ User userA = new User("Lguplus", 1); User userB = new User("minsupark", 29); List list = new ArrayList<>(); list.add(userA); list.add(userB); HashMap map = new HashMap<>(); map.put("lguplus", userA); map.put("minsupark", userB); model.addAttribute("user", userA); model.addAttribute("users", list); model.addAttribute("userMap", map); return "mvc/variable"; } // userName : lguplus, Age : 1 // userName : minsupark, Age : 29 // "user" : "lguplus" // "users" : [(userName : lguplus, Age : 1) , (userName : minsupark, Age : 29)] // "userMap" : (userName : lguplus, Age : 1) , (userName : minsupark, Age : 29)
Objet(1) 와 List(2) 그리고 Map(3)에 대한 변수 표현은 다음과 같다.
(1) Object
user.username: user의 username을 프로퍼티로 접근
user['username'] : lguplus
user.getUsername() : lguplus
(2) List
users[0].username : lguplus
list.get(0).getUsername() : lguplus
users[0]['username'] : lguplus
users[0].getUsername() : lguplus
users[1].getUsername() : minsupark
(3) Map
userMap['lguplus'].username : lguplus
map.get("lguplus").getUsername() : lguplus
userMap('lguplus']['username'] : lguplus
userMap['lguplus'].getUsername() : lguplus
Object ${user.username} = Lguplus ${user['username']} = Lguplus ${user.getUsername()} = Lguplus List ${users[0].username} = Lguplus ${users[0]['username']} = Lguplus ${users[0].getUsername()} = Lguplus Map ${userMap['lguplus'].username} = Lguplus ${userMap['minsupark']['username']} = minsupark ${userMap['lguplus'].getUsername()} = Lguplus
2-1 지역변수 선언
th:with을 사용하면 지역 변수를 선언해서 사용할 수 있다.
지역변수 - (th:with) 처음 사람의 이름은
지역변수 - (th:with) 처음 사람의 이름은 Lguplus
3. 기본객체
타임리프의 기본객체 제공은 다음과 같다.
${#request}
${#response}
${$session}
${#servletContext}
${#locale}
HTTP 요청 파라미터 접근 : param -> ${param.userId}
HTTP 세션 접근 : session -> ${session.sessionData}
스프링 빈 접근 : @ -> ${@heeloBean.hello('Spring!')}
@GetMapping("/mvc-objects") public String basicObjects(HttpSession httpSession){ httpSession.setAttribute("session-Data","Hello ErJuer01"); return "mvc/mvc-objects"; } @Component("Er-Bean") static class HelloBean{ public String hello(String data){ return "Hello World"+ data; } }
편의 객체 Request Parameter = session = spring bean =
해당 /mvc-objects URI에 parameter값을 붙인 요청을 하게 되면
http://localhost:8080/mvc/mvc-objects?paramData=carrot
화면에 보이는 뷰
HTML. 소스
4. 유틸리티 객체와 날짜
타임리프 유틸리티 객체들은 다음과 같다.
#message : 메시지, 국제화 처리
#uris : URI 이스케이프 지원
#dates : java.util.Date 서식 지원
#calendars : java.util.Calendar 서식 지원
#temporals : 자바 8 날짜 서식 지원 (LocalDateTime)
#numbers : 숫자 서식 지원
#strings : 문자 관련 편의 기능
#objects : 객체 관련 기능
#bools : boolean 관련 기능
#arrays : 배열 관련 기능
#lists, #sets, #maps : 컬렉션 관련 기능
#ids: 아이디 처리 관련 기능 제공
@GetMapping("/date") public String data(Model model){ model.addAttribute("localDateTime", LocalDateTime.now()); // LocalDateTime return "mvc/date"; }
default = yyyy-MM-dd HH:mm:ss = LocalDateTime - Utils ${#temporals.day(localDateTime)} = ${#temporals.month(localDateTime)} =
위의 코드는 java8에서 지원하는 LocalDateTime 객체를 thymeleaf로 전달했을 때의 예제이다.
은 Controller에서 넘겨준 값으로 보여주게 된다.
특히 8번째 줄의 temporals 유틸리티 객체들은 자바 8 날짜 서식을 지원해주기 때문에
${#temporals.day(localDateTime)} = 오늘 날짜 가 된다.
LocalDatieTIme 예시
간단하게 4가지의 표현식을 살펴보았고
약 3장동안 thymeleaf의 정리를 진행할 예정이다.
끝.
Reference.
https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-2
반응형
from http://erjuer.tistory.com/100 by ccl(A) rewrite - 2021-12-17 00:27:07