본문 바로가기

WINK-(Web & App)/Spring Boot 스터디

[2025 1학기 스프링 부트 스터디] 김민서 #2주차

반응형
정적 컨텐츠

스프링 부트는 정적 컨텐츠 기능을 자동적으로 제공한다!

이렇게 static 폴더에 아무 html 파일을 만들어주고 서버에 올리면 localhost:8080/파일 이름으로 접속시에 정적 컨첸츠가 뜨는 걸 확인할 수 있다.

 

MVC와 템플릿 엔진

package hello.hello_spring.controller;

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

@Controller
public class HelloController {
    @GetMapping("hello-mvc")
    public String helloMvc(@RequestParam("name") String name, Model model) {
        model.addAttribute("name", name);
        return "hello-template";
    }
}

컨트롤러 코드

<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>

html 코드

타임리프 템플릿은 HTML을 그대로 쓰고 파일을 서버 없이 바로 열어볼 수 있다.

required 옵션에서 default 값이 true기 때문에 기본으로 값을 넘겨야한다. false로 변경 시에 넘기지 않아도 됨.

 

API

@ResponseBody를 사용하면 HTTP body에 문자 내용을 직접 반환한다. (body 태그 아님)

 

@ResponseBody를 사용하고 객체를 반환하면 JSON으로 객체가 변환된다.

동작 과정은 이러하다.

  • HTTP의 BODY에 문자 내용을 직접 반환
  • viewResolver 대신에 HttpMessageConverter가 동작
  • 기본 문자처리: StringHttpMessageConverter
  • 기본 객체처리: MappingJackson2HttpMessageConverter
  • byte 처리 등등 기타 여러 HttpMessageConverter가 기본으로 등록되어 있음

 

반응형