본문 바로가기

웹 개발/Spring

[Spring 실습] View 환경설정

View 환경설정


스프링 부트는 resources/static/index.html을 만들면 welcome page로 제공한다.

 

1. resources/static 에 index.html 파일을 생성하자. 

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Hello</title>
</head>
<body>
Hello
<a href="/hello">hello</a>
</body>
</html>

 

2. 서버를 재실행해보자.

 

=> 자세히 알아보고 싶으면 https://spring.io/ => project => Spring boot 에 문서를 참고하자. 

 

thymeleaf 

https://www.thymeleaf.org/

 

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

 

3. 컨트롤러 생성.

웹 애플리케이션의 첫번째 진입점은 컨트롤러이다. 컨트롤러를 생성해보자. 

 

hello.hellospring 경로에 controller 패키지를 생성한다. 

HelloController.java 

 

package hello.hello_spring.controller;

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

@Controller
public class HelloController {

    @GetMapping("hello")
    public String hello(Model model) {
        model.addAttribute("data", "hello!");
        return "hello";
    }

}

 

4. resources/templates 경로에 hello.html 파일 생성

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

=> <html xmlns:th="http://www.thymeleaf.org"> 를 적어주면 타임리프 문법을 사용할 수 있다. 

 

5. localhost:8080/hello 에 접속해보자. 

동작 방식


 

 

 

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

=> 'resources:templates/' + {ViewName} + '.html'

 

 

빌드하기


1. 터미널에서 ./gradlw build 를 입력해보자. 

 

 

 

2. build/libs 폴더에 들어가보자. 

cd build

cd libs

 

ls -arlth 로 확인해보면 jar 파일이 생성되었다 .

 

3. java -jar hello-spring-0.0.1-SNAPSHOT.jar

를 입력해보자. 스프링이 실행된다.  

실제 배포할 때 jar 파일을 서버에 넣고 jar 파일을 실행시키면 된다. 

 

*./gradlw clean build 잘 안될 때는 clean build를 해보자. 빌드 폴더 삭제 후 재 빌드 한다. 

 

 

 

 

 

* 인프런 '스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술' 강의를 참고하여 작성했습니다.