View환경설정 - Welcome Page 만들기
- 스프링 부트에서는 static/index.html을 등록하면 Welcome Page 기능을 제공
▽ resources/static/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Hello World!</h1>
<a href="/hello">Hello</a>
</body>
</html>
▽ main/java/com.example.demo.controller/HelloController.java
package com.example.demo.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";
}
}
- @Controller : 컨트롤러의 역할을 수행한다고 명시(Annotation)
- @GetMapping("hello") : localhost:8080/hello 접속 시 아래 함수를 실행하라고 알려주는 역할
- model.addAttribute : 모델을 통해 값을 전달하고자 할 때 , key-value 쌍으로 전달함
- return "hello" : hello.html 파일을 찾아서 렌더링하라는 의미
> 컨트롤러에서 리턴 값으로 문자를 반환하면 viewResolver가 화면을 찾아서 처리
▽ resources/templates/hello.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>
- thymeleaf : java 라이브러리, View Template Engine, 서버에서 클라이언트에게 응답할 브라우저 화면을 만드는 역할
- xmlns:th : th문법을 사용하기 위해 선언하는 네임스페이스
- th:text : 태그 안에 들어가는 텍스트 값 변수 사용 시 ${} 안에 작성
윈도우 cmd 에서 빌드하고 실행하기
- cmd 이동
- 프로젝트 폴더 이동
- gradlew build
- build/libs 에서 java -jar demo-0.0.1-SNAPSHOT.jar 실행
'BACKEND > Spring' 카테고리의 다른 글
[ 인프런 - 스프링 입문 (김영한님) 강의 정리 ] 2. 스프링 웹 개발 기초 (0) | 2022.12.25 |
---|