Spring(기초)-2021.12.09

Jonguk Kim·2021년 12월 9일
0

Spring 기초

목록 보기
2/5

1. 정적 컨텐츠

  1. http://localhost:8080/hello-static.html 요청
  2. 화면 그대로 전달함

2. MVC와 템플릿 엔진

MVC: Model, View, Controller

@Controller
  public class HelloController {
      @GetMapping("hello-mvc")
      public String helloMvc(@RequestParam("name") String name, Model model) {
          model.addAttribute("name", name);
          return "hello-template";	// templates/hello-template.html
      }
}
// @RequestParam("가져올 데이터의 이름") [데이터타입] [가져온데이터를 담을 변수]
  1. http://localhost:8080/hello-mvc?name=spring 요청
  2. 컨트롤러에서 리턴 값으로 문자를 반환하면 뷰 리졸버( viewResolver )가 화면을 찾아서 처리
    ( templates/hello-template.html )

3. API

  • @ResponseBody 문자 반환
@Controller
  public class HelloController {
      @GetMapping("hello-string")
      @ResponseBody
      public String helloString(@RequestParam("name") String name) {
          return "hello " + name;
      }
}
  • @ResponseBody 객체 반환
@Controller
  public class HelloController {
      @GetMapping("hello-api")
      @ResponseBody
      public Hello helloApi(@RequestParam("name") String name) {
          Hello hello = new Hello();
          hello.setName(name);
          return hello;			// 객체 리턴하면 JSON으로 반환
      }
      static class Hello {
          private String name;
          public String getName() {
              return name;
	  }
          public void setName(String name) {
              this.name = name;
          } 
      }
}

  • @ResponseBody 를 사용하면 뷰 리졸버( viewResolver )를 사용하지 않음
  • viewResolver 대신에 HttpMessageConverter 가 동작
    • 기본 문자처리: StringHttpMessageConverter (문자 그대로 반환)
    • 기본 객체처리: MappingJackson2HttpMessageConverter (JSON으로 반환)
  1. http://localhost:8080/hello-api 요청
  2. @ResponseBody 를 사용하고, 객체를 반환하면 객체가 JSON으로 변환됨
profile
Just Do It

0개의 댓글