[Spring 기초] View 환경설정

Max·2023년 1월 3일
0

Spring

목록 보기
5/7


Welcome Page

  • 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>

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

정적 페이지

  • hello-static.html
<!DOCTYPE HTML>
<html>
<head>
  <title>hello static</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
정적컨텐츠
작성한 화면 그대로를 보여주며 무언가 작동은 불가능합니다!
</body>
</html>

"hello-static.html" 파일은 정적 화면으로 요청시 그대로 화면이 출력이 된다.

동적 페이지

thymeleaf을 이용해 동적 페이지 생성

  • HelloController
import org.springframework.stereotype.Conrtoller;
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";
    }
}
  • java>hello>hello-spring>controller 페키지를 생성하고 HelloController를 생성한다.
  • @GetMapping("/hello")는 웹 애플리케이션으로 /hello로 들어왔을 때 해당 메소드를 실행한다.
  • Model에 key인 "data"의 "hello"라는 데이터를 넘긴다.
  • hello를 return한다.

  • hello.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymelead.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>
  • resource>template에서 hello.html 생성한다.
  • thymelead을 사용하기 위해 위에서 선언을 해준다.
  • ${data}는 위 HelloController의 Modle.addAttribute()에서 hello을 치환한다.
  • 실행을 시키면 '안녕하세요, hello'가 출력 되는 것을 확인할 수 있다.

동작

  • 'localhost:8080/hello' 요청을 보내면 스프링 부트 내에 톰켓잉 hello에 대해 물어본다.
  • Controller 내에 hello에 주소가 매핑(GetMapping) 되어 있는 메소드가 있는지 확인을 한다.
    • 확인 했을 때 있으면 해당 메소드를 실행한다.
    • model을 생성하고 model.AddAttriibute()로 키값과 데이터를 추가한다.
    • viewResolver은 template에서 return하는 hello가 있는지 확인하고 처리를 한다.
profile
co_der

0개의 댓글

관련 채용 정보