[Spring] 정적 컨텐츠, MVC(템플릿 엔진), API

woozxn·2021년 6월 27일

Spring

목록 보기
2/8
post-thumbnail

🌕 정적 컨텐츠, MVC(템플릿 엔진), API

🌓 정적 컨텐츠

서버에서 별다른 작업이 이루어지지않고 html 파일을 그대로 넘겨줘서 보여주는 것
Spring boot는 static resources에 대한 기본 매핑 설정과 커스텀을 지원한다.

resources/static/hello-static.html

<!DOCTYPE HTML>
<html>
<head>
    <title>static content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head><body>
정적 컨텐츠 입니다.
</body>
</html>

웹 브라우저에서 내장 톰켓 서버로 URL을 전달하면 Server에서 hello-static 관련 컨트롤러가 있는지 찾고, 없으면 정적 컨텐츠를 찾는다.

🌓 MVC와 템플릿 엔진

MVC: Model, View, Controller

🌒 controller

hellospring/controller/HelloController.java

@Controller
public class HelloController {

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

🌒 view

resources/templates/hello-tamplate.html

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

서버연결없이 파일경로를 통해 열어봐도 내용을 볼 수있는데(thymeleaf기능)
그 경우 hello! empty 부분을 출력한다. 템플릿 엔진을 사용하면 controller에서 name 파라미터를 받고 있으므로 get 방식으로 parameter를 넘겨주어 해당 내용 값으로 치환되어 출력한다.

  1. hello-mvc?name=woojin 으로 요청이 들어온다
  2. server를 통해 controller에 전달한다
  3. name parameter를 받아서 처리 후 viewResolver로 전달한다
  4. viewResolver는 view와 controller를 연결 해 준다.
  5. 넘어온 값을 Thymeleaf 템플릿 엔진 처리로 변환하여 웹브라우저로 response 한다.

🌓 API

🌒 @ResponseBody 문자 반환

@Controller
public class HelloController {

    @GetMapping("hello-string")
    @ResponseBody
    public String helloString(@RequestParam("name") String name) {
        return "hello " + name;
    }

@ResponseBody를 사용하면 viewResolver를 사용하지 않는다. 대신 Http의 Body에 문자 내용을 직접 반환한다. (not html body tag)

🌒 @ResponseBody 객체 반환

@Controller
public class HelloController {

    @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를 사용하고, 객체를 반환하면 기본값으로는 객체가 JSON으로 변환됨

🌒ResponseBody 사용 원리

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

profile
1a2a3a4a5a

0개의 댓글