//컨트롤러
model.addObject("식별자", dto);
//html에서 사용할 때
→ th:text="${식별자.필드명}"
→ th:text="${식별자['필드명']}"
→ th:text="${식별자.get필드()}"
@Data
public class PersonDto {
private String pname;
private int age;
private String phone;
}
@GetMapping("/")
public String home(Model model) {
log.info("home()");
//Dto 활용
PersonDto person = new PersonDto();
person.setPname("홍길동");
person.setAge(20);
person.setPhone("010-1234-5678");
//person을 "pe"로 호출한다.
model.addAttribute("pe", person);
return "home";
}
<h2>연락처</h2>
<p>이름 : <span th:text="${pe.pname}"></span></p>
<p>이름 : [[${pe.pname}]]</p>
<p th:text="'이름 : ' + ${pe.pname}"></p>
<p>나이 : [[${pe['age']}]]</p>
<p>연락처 : [[${pe.getPhone()}]]</p>
식별자 앞에 session.
을 붙인다.
session.setAttribute("식별자", data);
→ th:text="${session.식별자}"
@GetMapping("second")
public ModelAndView second(HttpSession session){
log.info("second()");
ModelAndView mv = new ModelAndView();
mv.setViewName("second");
//로그인을 성공했다면(가정)
session.setAttribute("id", "user01");
return mv;
}
<p>Session에서 데이터 꺼내기</p>
<p th:text="${session.id} + '님 반갑습니다.'"></p>
<p>Hello world</p>
<p><a th:href="@{logout}">[로그아웃]</a></p>
<hr>
${session.id}
으로 가져온 아이디 user01
이 호출되었다.
참고) 자바스크립트에서 꺼낼 때 : let val = [[${session.식별자}]]
주로 javascript에서 사용한다.
rttr.addFlashAttribute("식별자", data);
→ let 변수 = [[${식별자}]];
값이 없으면 null.
if(변수 != null) ← 조건식 작성시 활용
로그아웃 처리 프로세스에 활용!
페이지에서 로그아웃 버튼을 누르면 home페이지로 리다이렉트하면서 메세지를 전달하고 로그아웃처리하는 방식으로 샘플링하였다.
두번째 페이지에서 로그아웃 버튼을 누르면 home페이지로 설정한 메인 페이지로 redirect 되면서 알림창이 뜬다.
@GetMapping("logout")
public String logout(RedirectAttributes rttr){
log.info("logout()");
String view = "redirect:/";
String msg = "로그아웃";
rttr.addFlashAttribute("msg", msg);
return view;
}
<script th:inline="javascript">
let m = [[${msg}]];
if(m != null){
alert(m);
}
</script>
msg
를 식별자로 불러오고 alert
명령어로 알림창을 띄운다.
th:block
- 제어문 및 객체 설정에 사용하는 태그.
- 일반적으로는 조건식, 반복식 등에 활용한다.
- 상위 요소가 지정되지 않은 객체의 출력에도 활용.
th:block을 활용한 제어 속성
1) th:if - if문에 해당하는 속성.
th:unless - if문의 else에 해당.
2) th:switch, th:case - switch, case에 해당하는 속성.
3) th:each - for문에 해당하는 속성.
<th:block th:each="변수:${목록}>...</th:block>
<th:block th:each="변수,status:${목록}">
status 항목을 사용하면 반복 상태의 정보를 구할 수 있음.
- index : 반복 순번(0부터 시작)
- count : 반복 횟수(1부터 시작)
- odd : 홀수 행인지 확인(홀수행이면 true)
- even : 짝수 행인지 확인(짝수행이면 true)
- first : 첫번째 행인지 확인(첫 행이면 true)
- last : 마지막 행인지 확인(마지막 행이면 true)
- size : 총 반복수(요소 수)
- current : 현재 반복이 수행되는 요소
참고) List(목록)의 null 체크 : ${#lists.isEmpty(목록)}
객체(DTO)의 null 체크 : ${#object.isNull(dto)}
@GetMapping("fourth")
public ModelAndView fourth(){
log.info("fourth()");
ModelAndView mv = new ModelAndView();
mv.setViewName("fourth");
mv.addObject("id", "hong01");
mv.addObject("age", 25);
List<PersonDto> pList = new ArrayList<>();
for(int i = 0; i<5; i++){
PersonDto per = new PersonDto();
per.setPname("사람" + i);
per.setAge(20 + i);
per.setPhone("010-1234-567" + i);
pList.add(per);
}
mv.addObject("pList", pList);
return mv;
}
ModelAndView
로 사용자의 id와 age를 각각 hong01
, 25
로 넘겨주었다.
그리고 리스트를 만들어 setPname
, setAge
, setPhone
의 값을 1씩 증가하게끔 for문으로 감싸주었다.
th:if
와 th:switch
활용
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<h2>th:if</h2>
//id변수가 null이 아니라면 id값과 p태그의 내용을 출력한다.
<th:block th:if="${id != null}">
<p th:text="${id} + '님 반갑습니다.'"></p>
</th:block>
<th:block th:unless="${id != null}">
<p>안녕하세요.</p>
</th:block>
<hr>
<h2>th:switch</h2>
//age값을 10으로 나눠 case에 해당하는 값의 p태그를 출력한다.
<th:block th:switch="${age/10}">
<p th:case="2">당신은 20대 입니다.</p>
<p th:case="3">당신은 30대 입니다.</p>
<p th:case="4">당신은 40대 입니다.</p>
</th:block>
th:each
를 활용한 반복문
<h2>th:each</h2>
<ul>
//만약 리스트가 비어있을 경우
<th:block th:if="${#lists.isEmpty(pList)}">
<li>출력할 목록이 없습니다.</li>
</th:block>
//else
<th:block th:unless="${#lists.isEmpty(pList)}">
//반복문 th:block th:each="변수,status:${목록}"
<th:block th:each="item,status:${pList}">
<fieldset>
//캡션 제목 count 증가
<legend th:text="${status.count}"></legend>
//이름, 나이, 연락처 count 증가
<li th:text="'이름 : '+ ${item.pname}"></li>
<li th:text="'나이 : '+ ${item.age}"></li>
<li th:text="'연락처 : '+ ${item.phone}"></li>
</fieldset>
</th:block>
</th:block>
</ul>
Thymeleaf 내에서의 연산식 활용
1) 산술 연산 : +, -, *, /, %
2) 비교 연산 : ==, !=, >, >=, <, <=
3) 논리 연산 : &&, ||, !
4) 조건 연산 : (조건식) ? A : B
5) 기본 표현식(Default Expression. 또는 Elvis Operator)
th:text="${data}?:값1"
➡ data가 null이 아니면 data, null이면 '값1'을 출력
2023.05.30 작성