Spring/스프링 입문 - 스프링 부트, 웹 MVC, DB 접근 기술

3. View 환경설정 | Welcome Page | Controller로 Thymeleaf 템플릿 엔진 동작 확인

DEV-HJ 2022. 6. 15. 22:35
반응형

1. 스프링 부트가 제공하는 Welcome Page 기능

- resource/static 폴더에 index.html 을 올려두면 Welcome Page가 된다

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
hello
<a href="/hello">hello</a>
</body>
</html>

 

2. Thymeleaf 템플릿 엔진

- 템플릿 엔진을 쓰면 위 사진의 정적 페이지를 동적으로 만들수 있다.

- Thymeleaf 공식 사이트 : https://www.thymeleaf.org/

- 스프링 공식 튜토리얼 : https://spring.io/guides/gs/serving-web-content/

- 스프링부트 메뉴얼 : https://docs.spring.io/spring-boot/docs/2.3.1.RELEASE/reference/html/spring-boot-features.html#boot-features-spring-mvc-template-engines

 


3. Controller로 Thymeleaf 템플릿 엔진 동작 확인

@GetMapping(" ")

 

HelloController.java

package hello.hellospring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {

    @GetMapping("/hello")
    public String hello(Model model){
        model.addAttribute("data", "hello!!");// data = 키, hello!! = 값
        
        // hello란 html을 찾아서 Data를 렌더링 시켜라
        return "/hello";
    }

}

 

hello.html

<!DOCTYPE html>
<!-- thymeleaf 템플릿 엔진 선언 -->
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!-- thymeleaf 문법으로 동적 Page로 변경 | ${data}는 Model에서 넘긴 key 값 -->
<p th:text="'안녕하세요. ' + ${data}" >안녕하세요. 손님</p>
</body>
</html>

 

Thymeleaf 템플릿 엔진 동작결과 화면

 

Thymeleaf 템플릿 엔진 동작 환경 그림

 

 


<HelloController.java>

Model이란?

Model은 HashMap 형태를 갖고 있으며 Key, Value 값을 가지고 있다.

또한 addAttribute() 같은 기능을 통해 모델에 원하는 속성과 그것에 대한 값을 주어진 뷰에 전달한다.

Spring에서 Controller의 메서드를 작성할 때 Model이란 타입을 파라미터로 지정할수 있다.

Model 객체는 jsp에 컨트롤레에서 생성된 데이터를 담아서 전달하는 역할을 한다.

이를 이용해서 JSP와 같은 뷰(View)로 전달해야 하는 데이터를 담아서 보낼수있다.

메서드의 파라미터에 Model타입이 지정된 경우에 Spring은 Model타입의 객체를 만들어서 메서드에 주입한다

 

인텔리제이 에선 attributeName, attributeValue 표시도 뜬다 ↓

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","스프링!!"); //data = 키, 스프링!! = 값
        return "hello";
    }
}

<index.html>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
hello
<a href="/hello">hello</a>
</body>
</html>

<hello.html>

${data} 이걸로 컨트롤러에서 설정한 값 출력

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!-- 키인 data로 값을 출력 -->
<p th:text="'안녕하세요. ' + ${data}" >안녕하세요. 손님</p>
</body>
</html>

 


MVC -> Model View Controller

지금은 MVC 스타일로 많이하지만, 옛날엔 Controller, View가 분리 되어있지 않았다. (모델1 방식)

그래서 하나의 View에 몇천줄씩 넘어가고 유지보수 하기 오래걸렸다.

View 는 화면을 그리는데 모든 역량을 집중해야 하고,

Controller는 비지니스 로직, 내부적인걸 처리하는데 집중해야 한다.
그래서 모델2 부터는 두개를 쪼갰다.


템플릿 엔진 이란? ↓

https://usefultoknow.tistory.com/entry/%ED%85%9C%ED%94%8C%EB%A6%BF-%EC%97%94%EC%A7%84Template-Engine-%EC%9D%B4%EB%9E%80

 

템플릿 엔진(Template Engine) 이란?

템플릿 엔진이란 템플릿 양식과 특정 데이터 모델에 따른 입력 자료를 합성하여 결과 문서를 출력하는 소프트웨어(또는 소프트웨어 컴포넌트)를 말합니다. * Template : 공통적인 프레임을 미리 제

usefultoknow.tistory.com



<HelloController.java>

@RequestParam 은?

@RequestParam 어노테이션은 HttpServletRequest 객체와 같은 역할을 한다.

HttpServletRequest의 getParameter() 메서드가 @RequestParam 어노테이션과 같다.

 

@RequestParam 은 요청 매개변수에 들어있는 기본 타입 데이터를 메서드 인자로 받아올 수 있다.

여기서 요청 매개변수란 URL 요청의 localhost:8080?username=value&age=value 의 쿼리 매개변수와,

HTML 태그의 Form 데이터가 해당한다.

 

HTTP GET으로 요청을 보내면 무조건 URL 끝에 쿼리스트링으로 key=value 형식으로 날아가기 때문에 굳이 Content-Type 헤더가 필요 없다.

package hello.hellospring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class HelloController {

    @GetMapping("hello")
    public String hello(Model model){
        model.addAttribute("data","스프링!!");// data = 키, 스프링!! = 값
        return "hello";
    }

    @GetMapping("hello-MVC")
    public String helloMvc(@RequestParam(value = "name", required = true) String name,
                           Model model)
    {
        model.addAttribute("name", name);
        return "hello-remplate";
    }
}

<hello-remplate.html>

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p th:text="'hello. ' + ${name}" ></p>
</body>
</html>

 

반응형