[스프링 입문] 웹 개발 방법 (정적 컨텐츠, MVC와 템플릿 엔진, API)

강신현·2022년 8월 2일
0

✅ @ResponseBody

1. 정적 컨텐츠

서버에서 수행하는 과정 없이 파일(html)을 그대로 웹브라우저로 내려주는 방법

  1. 스프링은 우선적으로 hello-static이라는 컨트롤러가 있는지 찾는다.
  2. 없다면 resource: static 에서 hello-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>

2. MVC와 템플릿 엔진

JSP, PHP 같은 템플릿 엔진이 서버에서 html 동적인 처리를 한 뒤에 웹 브라우저로 내려주는 방법
이를 위해 MVC (Model, View, Controller) 이용

  • 보여지는 화면(View)과 비즈니스, 내부 로직 부분(Controller)을 분리하기 위함
  1. helloController 에 메서드가 매핑되어 있으므로 내부 로직 처리 후 hello-template으로 리턴
  2. 템플릿 엔진이 html로 변환
  • Controller
@GetMapping("hello-mvc")
public String helloMvc(@RequestParam("name") String name, Model model) {
    model.addAttribute("name", name);
    return "hello-template";
}
  • hello-template
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>

3. API

html 파일 자체가 아니라 Json 같은 데이터 포맷으로 클라이언트에게 전달하는 방법

- @ResponseBody 문자 반환

  1. @ResponseBody 를 사용하여 뷰 리졸버( viewResolver )를 사용하지 않는다.
  2. HTTP의 BODY에 문자 내용을 직접 반환
  • Controller
@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name) {
    return "hello " + name;
}

- @ResponseBody 객체 반환

  1. @ResponseBody 사용
  2. 객체를 반환하면 객체가 JSON으로 변환
  • Controller
@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

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

강의 출처

[인프런 - 김영한] 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술

profile
땅콩의 모험 (server)

0개의 댓글