HJW's IT Blog

Spring 웹 개발 기초 본문

SPRING

Spring 웹 개발 기초

kiki1875 2024. 11. 25. 13:38

HTML? Controller?

hello-static.html 이라는 요청이 들어오면, 우선 hello-static 관련 컨트롤러가 있는지 찾아본다. Mapping 된 컨트롤러가 없을 경우, Sprin 은 /static 폴더 내에서 정적 컨텐츠를 찾아 반환한다.

@Controller
public class HelloController {
 @GetMapping("hello")
 public String hello(Model model) {
 model.addAttribute("data", "hello!!");
 return "hello";
 }
}

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
 <title>Hello</title>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'안녕하세요. ' + ${data}" >안녕하세요. 손님</p>
</body>
</html>

 

 

  • 위와 같은 controller 와 html 이 있을 경우, 요청이 들어올 시, controller mapping 을 통해 해당 메서드가 있는것을 확인한다. ViewResolver에 return 의 string 과 같은 이름의 html 을 찾아 Thymeleaf 템플릿 엔진에 넘긴다.
  • Template Engine 이 렌더링을 하여 변환된 html 을 브라우저에 반환한다.

API

    @GetMapping("hello-string")
    @ResponseBody
    public String helloString(@RequestParam("name") String name){
        return "hello " + name;
    }
  • GetMapping() 어노테이션은 HTTP GET 메서드를 처리한다.
  • ResponseBody() 는 메서드의 반환값을 HTTP 응답 본문에 포함하도록 지정한다.
  • 해당 예시의 경우, 문자열 hello {name} 이 반환되는 것이다.
  • 이전 예시와 다른점은, html 을 내리냐 마느냐의 차이이다. 이번 예시의 경우, 문자열 자체를 반환하는 것이다.

    @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;
        }
    }

이렇게 객체를 넘겨준다면 어떻게 될까?

{
  "name": "kim"
}

@ResponseBody 동작 원리

 

@ResponseBody 어노테이션을 사용하게 되면, Spring 은 View Resolver 를 거치지 않고 HTTP의 response body 에 직접 객체를 json 형식으로 담아 보내게 된다.

이때, 반환값은 HttpMessageConverter 에 의해 클라이언트에게 보내지기 전, Object → Json / XML 형식으로 변환이 이루어 진다. 이때, 단순 string 의 경우 StringHttpMessageConverter 가 사용되지만, 객체의 경우 MappingJackson2HttpConverter 가 사용되는 것이 일반적이다.

@RestController 내부에서 사용 될 경우, 모든 메서드는 @ResponseBody 가 있는 것 처럼 동작한다.