솔적솔적

스프링 웹 개발 - 템플릿 엔진 thymeleaf 본문

Back-end/Spring Boot

스프링 웹 개발 - 템플릿 엔진 thymeleaf

카드값줘체리 2022. 1. 25. 03:49

 

템플릿 엔진을 사용하여 웹브라우저에 입력한 값이 나오게끔 해보자.

 

 

 

먼저, 

1. HelloController안에 Get매핑내용입력

@GetMapping("hello-mvc")
	 public String helloMvc(@RequestParam(name = "name", required = false) String name, Model model) {
	 model.addAttribute("name", name);
	 return "hello-template";
	 }

 

 

 

그리고, 

2. templates 안에 hello-template.html 만들기

<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">아하!</p>
</body>

thymeleaf를 사용하면 1번의 값으로 2번을 치환하기 때문에 서버없이 보기 가능하다.

즉, 1번의 값으로 내용물이 바뀌게 된다.

 

 

 

 

 

실행하면 에러나옴

오류: parameter 'name' for method parameter type String is not present

 

name이 있어야한다.

public String helloMvc(@RequestParam(name = "name", required = false) String name, Model model)

required라는 옵션이 있는데 여기에 기본의 값을 넘겨야한다.

따라서 false로 작성 후 다시 실행

이렇게 되어진 원리는

1번 name은 ‘맘대로써보자’ 로바뀌고

2번도 name은 ‘맘대로써보자’ 바뀌고

hello-template.html에서도 name은 모델에서 값을 꺼내는 것.

따라서 ‘맘대로써보자’라고 했던 값이 나오는 것이다.

 

  1. 웹 브라우저에서 localhost:8080/hello-mvc를 넘기면
  2. 내장 톰켓 서버를 먼저 거치며 “어! hello-mvc가 왔네!” 하고 스프링에 던지고helloController에 넘김
  3. helloController에 맴핑된 메소드를 호출
  4. return은 hello-template, model은 name : 맘대로써보자. 라는 것을 또 넘긴다.
  5. 넘긴 곳은 viewResolver. 여기서처리해달라하고 thymeleaf 랜더링해서 변환한 html을 웹브라우저에 넘긴다.
  6. 스프링의 view를 찾아주고 템플릿에 연결해주는 viewResolver가 templates/hello-template.html라는 return과 똑같은 얘를 찾아서 thymeleaf템플릿 엔진에게

 

[참조자료] 인프런 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술 v20211