[스프링 MVC 1편] HTTP 응답

강신현·2022년 9월 21일
0
post-thumbnail

✅ @RestController


📕 응답

1. 정적 리소스

웹 브라우저에 정적인 HTML, css, js를 제공할 때는, 정적 리소스를 사용한다.

2. 뷰 템플릿 사용

웹 브라우저에 동적인 HTML을 제공할 때는 뷰 템플릿을 사용한다.

  • 경로 : src/main/resources/templates

  • 뷰 템플릿

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p th:text="${data}">empty</p>
</body>
</html>
  • controller
@Controller
public class ResponseViewController {

    @RequestMapping("/response-view-v1")
    public ModelAndView responseViewV1() {
        ModelAndView mav = new ModelAndView("response/hello")
                .addObject("data", "hello!");
        return mav;
    }

    @RequestMapping("/response-view-v2")
    public String responseViewV2(Model model) {
        model.addAttribute("data", "hello!!");
        return "response/hello";
    }
}
  1. String을 반환하는 경우 - View or HTTP 메시지
    @ResponseBody 가 없으면 response/hello 로 뷰 리졸버가 실행되어서 뷰를 찾고, 렌더링 한다.
    @ResponseBody 가 있으면 뷰 리졸버를 실행하지 않고, HTTP 메시지 바디에 직접 response/hello 라는 문자가 입력된다.

  2. Void를 반환하는 경우
    명시성이 너무 떨어지고 이렇게 딱 맞는 경우도 많이 없어서, 권장하지 않는다.

3. HTTP 메시지 사용

HTTP API를 제공하는 경우에는 HTML이 아니라 데이터를 전달해야 하므로,
HTTP 메시지 바디에 JSON 같은 형식으로 데이터를 실어 보낸다.

@ResponseStatus(HttpStatus.OK)
@ResponseBody
@GetMapping("/response-body-json-v2")
public HelloData responseBodyJsonV2() {
    HelloData helloData = new HelloData();
    helloData.setUsername("userA");
    helloData.setAge(20);

    return helloData;
}

- 💡 @RestController

@Controller 대신에 @RestController 애노테이션을 사용하면, 해당 컨트롤러에 모두 @ResponseBody 가 적용되는 효과가 있다.
따라서 뷰 템플릿을 사용하는 것이 아니라, HTTP 메시지 바디에 직접 데이터를 입력한다.
이름 그대로 Rest API(HTTP API)를 만들 때 사용하는 컨트롤러이다.


강의 출처

[인프런 - 김영한] 스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술

profile
땅콩의 모험 (server)

0개의 댓글