Post

Spring 스프링 입문 - 2. 스프링 웹 개발 기초

스프링 웹 개발 기초

정적 컨텐츠

resources/static/hello-static.html

1
2
3
4
5
6
7
8
9
10
<!DOCTYPE HTML>
<html>
<head>
 <title>static content</title>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
정적 컨텐츠 입니다.
</body>
</html>
  • 실행: http://localhost:8080/hello-static.html
    img

  • 주소 값과 관련있는 컨트롤러가 없으면 resources의 static 폴더에서 화면을 자동으로 찾아준다.

MVC와 템플릿 엔진

  • MVC: Model, View, Controller
Controller
1
2
3
4
5
6
7
8
@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-template.html

1
2
3
4
5
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>
  • 실행: http://localhost:8080/hello-mvc?name=spring

img

  • 주소 값 뒤의 ? 뒤에 있는 name=spring은 name이라는 param에 value가 spring인 { key : value } 형식으로 넘어온다.
  • 이것을 Controller에서 @RequestParam("name")으로 name이라는 param을 String name으로 받는다.
  • name을 model.addAttribute("name", name)을 통해 모델에 넣고 뷰에 넘긴다.
  • View에서는 ${name}이라는 Thymeleaf 문법을 통해 받은 모델에서 name을 사용한다.

API

@ResponseBody 문자 변환
1
2
3
4
5
6
7
8
@Controller
public class HelloController {
     @GetMapping("hello-string")
     @ResponseBody
     public String helloString(@RequestParam("name") String name) {
         return "hello " + name;
     }
}
  • @ResponseBody 를 사용하면 뷰 리졸버( viewResolver )를 사용하지 않음
  • 대신에 HTTP의 BODY에 문자 내용을 직접 반환(HTML BODY TAG를 말하는 것이 아님)
@ResponseBody 객체 반환
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@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 사용 원리

img

  • @ResponseBody를 사용
    • HTTP의 BODY에 문자 내용을 직접 반환
    • viewResolver 대신에 HttpMessageConverter 가 동작

    • 기본 문자처리: StringHttpMessageConverter
    • 기본 객체처리: MappingJackson2HttpMessageConverter
    • byte 처리 등등 기타 여러 HttpMessageConverter가 기본으로 등록되어 있음
  • 참고: 클라이언트의 HTTP Accept 해더와 서버의 컨트롤러 반환 타입 정보 둘을 조합해서 HttpMessageConverter 가 선택된다.

References: 김영한 - [스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술]
This post is licensed under CC BY 4.0 by the author.