Spring boot에서 view(HTML)를 처리하는 기본 방식 중 하나.
인텔리제이 프로젝트 생성 화면
Spring Boot DevTools 포함(프로젝트 생성 시)
application.properties에 devtools 설정
#devTools setting
spring.devtools.livereload.enabled=true
spring.devtools.restart.enabled=true
spring.thymeleaf.cache=false
File > Setting...
- Build, Execution, Deployment > Compiler
-> Build project automatically
체크
Allow auto-make to start even if developed application is currently running
체크1) templates 폴더에 HTML 문서로 작성.
2) <html> 태그에 xmlns:th="http://www.thymeleaf.org"속성 포함.
html 페이지에서 thymeleaf 속성 포함시키기
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
1) 기본적인 데이터 출력은 EL 형식을 사용 : ${...}
2) 링크(url) : @{link}
(a 태그나 form 태그의 action 등)
3) 객체의 필드(멤버변수) : *{field}
@Controller
@Slf4j
public class HomeController {
@GetMapping("/")
public String home(Model model) {
log.info("home()");
//문자열 전송
model.addAttribute("d1", "서버로부터 <b>전송</b>");
String str = "결과 메시지";
int num = 300;
model.addAttribute("d2", str);
model.addAttribute("d3", num);
PersonDto person = new PersonDto();
person.setPname("홍길동");
person.setAge(20);
person.setPhone("010-1234-5678");
model.addAttribute("pe", person);
return "home";
}
컨트롤러 소스에서 home.html
로 @Getmapping
을 걸어주고 해당 페이지에서 사용할 속성을 입력한다.
<!DOCTYPE html>
//타임리프 사용
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Thymeleaf Home</title>
<script th:inline="javascript">
let m = [[${msg}]];
if(m != null){
alert(m);
}
</script>
</head>
<body>
<h1>Thymeleaf 첫 페이지</h1>
<p th:text="${d1}"></p>
<p>[[${d2}]]</p>
<p th:utext="${d1}"></p>
<p>[(${d1})]</p>
<input type="number" th:value="${d3}">
<hr>
<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>
<hr>
<a th:href="@{second}">[두번째]</a>
</body>
</html>
1. th:text
, th:utext
요소의 내용으로 출력할 때 사용하는 속성.
1) <p th:text="${...}"></p>
➡ innerText 형식
2) <p>[[${...}]]</p>
➡ innerText 형식
3) <p th:utext="${...}"></p>
➡ innerHTML 형식
4) <p>[(${...})]</p>
➡ innerHTML 형식
(innerHTML과 innerText 형식의 차이는 문장 내의 태그 표현)
2. th:value
input 태그의 초기값으로 출력할 때 사용하는 속성.
3. th:inline
자바스크립트 태그에 사용하는 속성.
<script ht:inline="javascript">...</script>
4. th:href
링크 연결 속성(<a>
태그에서 사용)
<a href="test?d1=100&d2=200">전달</a>
<a th:href="@{test(d1=100,d2=200)}">전달</a>
5. th:action
form 태그의 action 속성과 동일.
<form th:action="@{url}">
6. th:object
Dto와 같은 객체로 데이터를 전송한 경우 이 속성에 객체를 지정하고 필드의 데이터는 *{필드}
형식으로 가져올 수 있다.
2023.05.30 작성