김영한 님의 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술 강의를 보고 작성한 내용입니다.
https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-%EC%9E%85%EB%AC%B8-%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8/dashboard
정척 컨텐츠 : 파일을 그대로 클라이언트(웹 브라우저)에게 전달
SringBoot는 정적 컨텐츠를 static
에서 찾아서 제공
접속방법 : localhost:8080/파일명.html
JSP, PHP와 같은 것들이 템플릿엔진
템플릿엔진 : HTML을 그냥 주는 것이 아니라 서버에서 프로그래밍해서(HTML을 변형해서) 동적으로 준다
이를 위해 Controller, Model, View가 필요
View : 화면을 그리는데 집중
Controller : 비지니스 로직이나 서버 내부적인 것을 처리하는데 집중
Model : View에 필요한 데이터를 담는다
< HelloController >
@GetMapping("hello-mvc")
public String helloMVC(@RequestParam("name") String name, Model model) {
model.addAttribute("name", name);
return "hello-template";
}
@RequestParam
: 외부에서 파라미터를 받음
@RequestParam("name") String name
: 외부의 name을 String name으로 받음
return 하는 것은 html의 이름
< hello-template.html >
<p th:text="'hello ' + ${name}">hello! empty</p>
http://localhost:8080/hello-mvc
로 접속하면 에러 발생
에러 : Required request parameter 'name' for method parameter type String is not present
@RequestParam에 name이 지정되어 있는데 아무것도 전달되지 않았기 때문
해결 : http://localhost:8080/hello-mvc?name=spring
처럼 입력한다
@RequestParam
의 속성인 required
의 default 값은 true
서버에서 클라이언트에게 JSON 형식으로 데이터를 전달
MVC는 HTML에 데이터를 담아서 내리지만 API는 데이터를 바로 내린다
@ResponseBody
가 없으면 viewResolver가 동작
@ResponseBody
를 사용하면
HTTP의 Body에 직접 데이터를 넣어준다는 의미 ( HTTP에는 Header, Body가 존재 )
viewResolver 대신에 HttpMessageConverter
가 동작
클라이언트의 HTTP Accept 헤더와 서버의 컨트롤러 retun 타입 정보를 조합해서 HttpMessageConverter
가 선택된다
기본 문자처리: StringHttpMessageConverter
기본 객체처리: MappingJackson2HttpMessageConverter
byte 처리 등등 기타 여러 HttpMessageConverter
가 기본으로 등록되어 있음
< Controller >
@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name) {
return "hello " + name;
}
@ResponseBody
를 사용하면 뷰 리졸버( viewResolver )를 사용하지 않음 static class Hello {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@GetMapping("hello-api")
@ResponseBody
public Hello helloApi(@RequestParam("name") String name) {
Hello hello = new Hello();
hello.setName(name);
return hello;
}
@ResponseBody
를 사용하면서 객체가 반환되면 객체가 JSON으로 변환됨