티스토리 뷰

TIL

[Spring Boot] Controller: Response

호호홍얍얍 2022. 5. 28. 20:21

Controller는 http 요청/응답 처리를 하는 데 사용된다.

@Controller를 사용 시 Servlet 코드에 비해 매번 작성해야 하는 중복코드가 생략되고 스프링에서 대신해준다는 장점이 있다.

 

HTTP Response 의 구성

Response는 간략하게 상태줄 + 헤더 + 본문으로 구성되어 있다.

- 상태줄: HTTP/1.1 404 NOT FOUND

  • 요청에 대한 응답코드가 실려있다.

- 헤더: ContentType, location

  • ContentType: 없음, text/html, application/json
  • location: 리다이렉트할 페이지 url

- 본문: HTML / JSON

 

Controller-Response

  • Controller의 Return 타입에 따라 Response의 내용이 달라지게 되는데, 
  •  @ResponseBody 없이 String 으로 Response 받는다면, thymeleaf(View Resolver) 는 아래의 기본 설정대로 View를 찾는다. View Resolver는 DispatcherServlet으로부터 받은 View Name으로 View를 찾고, 전달 받은 Model로 View를 변환하여 View 객체를 반환해서 Response에 실어 보낸다.
    • preifx: classpath/templates/
    • suffix: .html
    • => resources/templates/hello.html 로 이동
    • 만약, return 값에 redirect:/{url} 이 들어있다면, Response는 헤더의 location에 redirect url 을 실어 간다.
  • @ResponseBody가 있다면, View를 제공하는 것이 아니라, Body에 해당 내용을 전달한다. 즉, ViewResolver 를 거치지 않고 Http Message Converter를 호출한다.
    • 문자가 왔을 때: String Converter가 호출됨
    • 객체가 왔을 때: JSON Converter가 호출됨
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2026/05   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함