본문 바로가기

Programming/Spring Boot

[Spring Boot] View 환경설정 (vscode)

정적 페이지 띄우기

  1. 정적 페이지 생성  ~/src/main/resources/static/index.html 
    스프링부트는 기본적으로 먼저 index.html을 찾으므로 가장 먼저 거쳐갈 파일 명은 index.html 로 해주자
  2. view 코드 작성 (index.html)
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        Hello
        <a href="/hello">hello</a>
    </body>
    </html>



  3. 서버 실행
    ~/src/main/java/패키지명/프로젝트명/프로젝트명Application.java 파일에서 Ctrl + F5 클릭해 프로젝트 실행
  4. localhost 확인 (아직 /hello 는 경로 컨트롤러 세팅을 해주지않아 에러 발생)

 

 


 

Thymeleaf를 활용한 컨트롤러 및 View 설정

  1. 컨트롤러 생성 
  2. 컨트롤러 코드 작성 (HelloController.java)
    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", "hello!!");
            return "hello";
        }
        
    }


  3. tymeleaf를 활용한 view 생성
  4. view 코드 작성 (hello.html)
    <!DOCTYPE html>
    <html xmlns:th="https://www.thymeleaf.org/">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <p th:text="'안녕하세요. '+ ${data}"></p>
    </body>
    </html>


  5. 정상동작 확인 (서버 재시작)
  6. 동작 원리

 

 

 

 

 

728x90