본문 바로가기

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

[2025 1학기 스프링 부트 스터디] 오세웅 #2주차

반응형

정적 컨텐츠

정적 컨텐츠는 파일 웹 브라우저에 그대로 전달하는 방식

 

static 폴더에 html파일을 생성하고 웹 브라우저에서 파일 이름을 호출하면 정적 파일이 그대로 넘어오게 된다.

톰캣 서버에서 요청을 받고 컨트롤러가 우선순위가 높기 때문에 먼저 컨트롤러에서 찾고

없으면 static에서 찾아서 있으면 그대로 출력하는 방식이다.

 

MVC와 템플릿 엔진

MVC: Model, View, Controler

 

Model : 핵심 로직과 데이터에 접근하는 역할

View : 사용자가 보는 UI 역할

Controler : 요청을 받고 데이터를 가공해서 돌려주는 역할

 

식당에 비유하면 다음과 같다.

 

실제 코드를 보면 다음과 같다.

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

 

요청이 오면 Controler에서 @RequestRaram 애너테이션을 통해 입력받은 name값을 model에 저장하고

template/hello-template.html 파일을 리턴한다. 

 

이 때 name을 입력받기 위해서는 http://localhost:8080/hello-mvc?name=spring처럼

뒤에 "?name=내용"을 입력해야한다.

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

 

hello-template.html가 웹 브라우저에 전달이 되는데 name이 model에 저장된 값으로 바뀌어서 전달된다.

 

hello-template.html에서 어떻게 model객체에 접근하는지 궁금해서 찾아봤는데

hello-template를 리턴한 메서드의 객체에는 참조가 가능하다고 한다.

 

 

API

API는 JSON이나 XML같은 데이터 형식으로만 주고받는 방식이다.

 

Controler
@GetMapping("hello-api")
@ResponseBody
public Hello helloApi(@RequestParam("name") String name){
    Hello hello = new Hello();
    hello.setName(name);
    return hello;
}
static class Hello {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}​

 

@ResponseBody가 API방식을 사용하는 애너테이션이고 메서드 결과를 View로 보내는 게 아니라

JSON형식으로 바로 웹 브라우저에 반환한다.

다른 형식도 있지만 거의 대부분 JSON방식을 사용한다.

 

위 코드에서 이 전 코드들과 다른 점은 객체를 반환하는 것이다.

 

@ResponseBody 애너테이션이 있으면 View가 아니라 Converter로 전달이 되는데 만약 문자열이면 StringConverter, JSON형식이면 JsonConverter로 전달된다.

반응형