spring view

YOONIVERSE·2023년 8월 25일
0

스프링

목록 보기
3/5

spring view 환경설정

welcome page 만들기

src/main/resources/static/index.html 파일 생성

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

http://localhost:8080 로 화면이 잘 뜨는지 확인

spring이 java 전반의 엔터프라이즈를 제공하기 때문에 필요한 정보를 잘 찾는 것도 중요하다.

spring.io 접속 > projects> springboot 에서 궁금한 것 검색가능

템플릿엔진을 쓰면 모양을 바꿀 수 있다.

웹애플리케이션에서 진입점이 컨트롤러이다.
src/main/java/practice.hellospring 에서 뉴패키지생성> [controller] 생성
생성된 controller 에서 [HelloController] 클래스 생성

스프링은 @Controller 라고 작성해줘야한다.

- HelloController.java 

package practice.hellospring.controller;

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

@Controller    // @Controller가 작성되면 자동으로 import 생성
public class HelloController {

    @GetMapping("hello") // 자동으로 import 생성, get방식을 말하는 것
    public String hello(Model model) {    // 자동으로 import 된다.
        model.addAttribute("data", "hello!!");  // key는 data, value는 hello!!
        return "hello"; // resources/templates/hello.html 가서 랜더링하라는 뜻
    }
}

웹 어플리케이션에서 /hello 호출 들어오면 HelloController.java 메서드가 호출된다.

src/main/resources/templates/hello.html

- hello.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">   // thymeleaf 템플릿엔진을 쓸 수 있다.
<head>
   <title>Hello</title>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF=8" />
</head>
<body>
<p th:text="'안녕하세요. ' + ${data}">안녕하세요. 손님</p>   // data는 HelloController.java의 model의 value값인 hello가 호출 된다.
</body>
</html>

localhost:8080/hello

*동작환경그림*

  • 컨트롤러에서 리턴 값으로 문자를 반환하면 viewResolver가 화면을 찾아서 처리한다.
    * 스프링 부트 템플릿엔진 기본 viewName 매핑
    * resources/templates/ {viewName}.html

tip📕

spring-boot-devtools 라이브러리를 추가하면 html 파일을 컴파일만 해주면 서버 재시작 없이 view파일 변경이 가능하다.
IntelliJ 컴파일 방법: menu>build>recompile

profile
스텝이 꼬이면 그것이 바로 탱고 💃

0개의 댓글