본문 바로가기

Spring/Spring

spring-boot View 환경 설정

index.html만들어서 쓰니까 바로 사용가능하네

resources - static - index.html

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Insert title here</title>
</head>
<body>
	<div>여기는 static폴더의 index.html파일입니다</div>
</body>
</html>

정적 페이지에요. 요청 받아서 그냥 파일을 그냥 던져준 것!

스프링은 거의 웹 전반에 대한 모든 걸 제공하고 있다.

스프링 부트는 좀 더 편하게 쓸 수 있게 해준다. 필요한 걸 찾는 능력이 중요하다.

spring.io 공홈이얌. 다양한 내용 찾아서 쓸 수 있어.

템플릿 엔진

템플릿 엔진은 페이지 내용을 바꾸거나 할 수 있도록 기능을 지원한다.

(스프링에서 제공하는 기본적인 Template Engines은 FreeMarker, Groovy, Thymeleaf, Mustache가 있다)

우리는 템플릿 엔진 중에 thymeleaf 템플릿을 쓰겠다.

https://www.thymeleaf.org/

https://docs.spring.io/spring-boot/docs/2.4.3/reference/html/spring-boot-features.html#boot-features-resttemplate

여기서 추가 학습이 가능하다 @.,@

일단 만들어봅시다.

controller패키지 만들고 HelloController.java 만듬

package hello.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";
	}
}


Spring 4.3부터 추가된 5가지의 어노테이션

@PostMapping

@GetMapping

@PutMapping

@DeleteMapping

@PatchMapping

https://nocount.tistory.com/143


ModelAndView 와 Model 차이점

ModelAndView는 뷰와 모델을 기술할 필요가 있을 때 사용하시면됩니다. Model은 이름 그대로 뷰로 전달할 모델값만 기술 하시면됩니다. View 도 있습니다. View 객체를 직접 전달할 때 사용 하시면됩니다.(위 예제에는 String 을 리턴했을 때에는 기본 View를 사용하도록했기 때문에(ViewResolver) View객체는 내부에서 처리 되기 때문에 보이지 않습니다.) 즉 적절하게 사용하시면됩니다. View정보를 따로 전달할 필요 없는데 ModelAndView 사용할 이유는 없겠죠. 심플하게 하시면 됩니다.

https://okky.kr/article/386045


템플릿 패키지 내에서 hello.html만드세용!

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Insert title here</title>
</head>
<body>
	<p th:text="'안녕하세요. ' +${data}">안녕하세요. 손님 <p>
</body>
</html>

th는 thymeleaf의 약자 th.

<html xmlns:th="http://www.thymeleaf.org">

<html xmlns:th="http://www.thymeleaf.org">이거 넣어주면 thymeleaf의 문법을 사용할 수가 있다.

localhost:8080/hello로 요청하면? 이렇게 뜬다.

컨트롤러의 model.addAttribute에 넣었던 "data"에 "hello"가 들어있는데.. 그게 ${data}에 들어있음


Thymeleaf 기본 사용법, 문법 예제 https://oingdaddy.tistory.com/112

HTML 한글 깨짐 방지 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />


웹 브라우저에서 localhost:8080/hello를 요청하면 톰캣 내장 서버가 어? 이거 달라는데?

컨트롤러를 살펴봐 hello가 있네? 이 url에 매칭 되고, 안에 들어 있는 소스코드 봐바. model매개 변수는 스프링이 넣어줌. return "hello"를 하게 되면, resources의 hello를 찾아. 데이터 넘겨.

templates폴더 밑의 hello.html을 찾아 렌더링 한다. (타임리프 템플릿 엔진이 처리를 해준다)

컨트롤러에서 리턴 값으로 문자를 반환하면, 뷰 리졸버(viewResolver)가 화면을 찾아서 처리한다.

-스프링 부트 템플릿엔진 기본 viewName 매핑

-resources:template/ + {ViewName} + .html

<p th:text="`안녕하세요.`+${data}">안녕하세요 </p> 이런 식으로 넘겨받았음.

컨트롤러를 통해 [안녕하세요 hello!! ]는 렌더링한다는 걸 이해는 했는데요. <p>태그 안에 내용은 왜 렌더링이 되지 않는 걸까요?!

thymeleaf 뷰 템플릿은 렌더링 시점에 태그 안의 내용을 렌더링 내용으로 치환해버리는 특징이 있다.

장점은? 렌더링 되기 전에도 html 내용을 그대로 볼 수 있다는 것!

이런 특징 때문에 <p> 태그 안 </p>의 내용은 렌더링 하지 않는다.

해당 포스팅은 인프런 김영한님의 스프링 강의를 따라가며 정리한 노트입니다 :)

반응형