스프링 입문 - 코드로 배우는 스프링 부트, 웹
본 블로그에서는 김영한의 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술 영상을 보면서 정리한 블로그이다.
다음과 같은 목차로 Intro는 구성이 된다.
Intro
1. 스프링 입문
2. 스프링 핵심 원리
3. 스프링 웹 MVC
4. 스프링 DB 데이터 접근 기술
5. 실전! 스프링 부트
초기 실습 및 환경설정
1. 먼저 스프링 프로젝트 관련해서 환경설정은 다음과 같다.
스프링 부트 스타터 사이트로 이동해서 스프링 프로젝트를 생성을 한다.
위의 사이트에 들어가서 자신의 환경설정에 맞게 설정을 합니다.
-> 다만 Dependencies는 다음과 같이 설정을 한다.
Spring the Web & Thymlead
Spring the Web : 웹을 만들때 필요한 개발자 툴이고
Thymleaf는 HTML 환경에서 필요한 자바 템플릿이다.
2. 다운받은 패키지를 intelliJ에 압축을 푼다.
3. main 폴더에 있는 파일을 실행시킨다. 그러면 다음과 같이 로고가 뜬다 ( 신기하댜 ) ㅎ
초기 실습 및 환경설정
1. src -> main -> resources -> static -> index.html 파일 생성
그 밑에 다음과 같은 코드를 적는다.
그리고 중단하고 실행하면 화면이 뜬다.
spring boot 자체가 index.html 파일을 찾아서 실행시키기 때문에 해당 화면이 뜨게 된다 .
2. thymeleaf 템플릿 엔진
템플릿 엔진이란?
서버 측에서 동적으로 html, css, javascript 생성하는 것
Thymeleaf
Integrations galore Eclipse, IntelliJ IDEA, Spring, Play, even the up-and-coming Model-View-Controller API for Java EE 8. Write Thymeleaf in your favourite tools, using your favourite web-development framework. Check out our Ecosystem to see more integrati
www.thymeleaf.org
이를 위해서 controller package를 다음과 같은 위치에 생성해준다.
- src
- main
- java
- com.exmple.demo
- controller
- com.exmple.demo
- java
- main
그리고 그 밑에 HelloController를 작성해준다.
코드를 간단하게 설명하자면 return hello는 hello.html 파일을 랜더링하라는 것을 의미한다.
즉 data 를 model을 통해 넘기면서 hello.html을 랜더링하는 코드이다.
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";
}
}
그 후 templates -> hello.html 파일을 생성을 하여 코드를 돌려본다.
그렇게 되면 ${data} 부분에 hello!! 라는 인자값이 들어가서 다음과 같은 화면이 뜨는 것을 확인할 수 있다.
<!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>
정확한 원리와 동작은 아직 잘 모르겠지만
그래도 이렇게 화면에 나오니 좀 신기했다 ㅎㅎ
참고로 윈도우 기준으로 빌드하는 방법은 다음과 같다.
해당 프로젝트까지 간 다음, 밑의 명령어를 치면 build가 된다.
{경로}> .\gradlew build