<Spring Boot> 3. View 환경설정

빡찌's avatar
Sep 19, 2024
<Spring Boot> 3. View 환경설정
프로젝트를 생성하고 실행시켰을 때 브라우저에 에러페이지가 난거
기억나쥬? > 당연하다 아무것도 안만들어 놨으니까
 
이제 기본적인 View 페이지를 만들어보겠따
 
notion image
먼저 resources 밑 static 폴더에 index.html 파일 생성 해준다
 
<!DOCTYPE HTML> <html> <head> <title>HELLO</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> Hello <a href="/hello">hello</a> </body> </html>
이거 넣어준다~
그리고 서버 껏다가 켜고 브라우저에서 확인해보자
notion image
짜란~
이까지 하면 웰컴페이지 잘 됐어용
근데 이건 프로그래밍이 아님
 

thymeleaf라는 템플릿 엔진을 써보자!

notion image
우선 이 밑에 패키지를 하나 파주고 컨트롤러 java class도 하나 파준다
 
package com.example.hellospring.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class HelloController { @GetMapping("hello") public String hello(Model model) { model.addAttribute("data", "hello!!"); return "hello"; } }
이렇게 해주고 resources 밑에 있는 templates로 가보자
notion image
html 파일 만들어주고
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>HELLO</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <p th:text="'안녕하세요. ' + ${data}" >안녕하세요. 손님</p> </body> </html>
<html xmlns:th="http://www.thymeleaf.org">
: 템플릿 엔진을 넣어준 것!
notion image
여기 있는 data 가 컨트롤러에 속성으로 넣어준
notion image
요 data임 그래서 ${data}는 data의 value인 hello!가 나옴
 
서버 다시 껏다 키고
localhost:8080/hello에 들어가보자
notion image
짜란
 
  • 컨트롤러에서 리턴 값으로 문자를 반환하면 뷰 리졸버(’viewResolver’)가 화면을 찾아서 처리한다
    • 스프링 부트 템플릿엔진 기본 viewName 매핑
    • ‘resources:templates/’ +{ViewName}+’.html’
 
<참고>
‘spring-boot-devtools’라이브러리를 추가하면, ‘html’ 파일을 컴파일만 해주면 서버 재시작 없이 View파일 변경이 가능함!
컴파일 방법: build → Recompile
Share article

prettytree