* 해당 시리즈는 인프런 김영한님 강좌인 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술 내용
강의를 학습하며 개인적으로 정리한 글이며, 저작권 문제나 잘못된 부분이 있다면 지적해주시면 감사하겠습니다.
파일을 그냥 웹 브라우저에 그대로 올려주는 것.
resources.static/hello-static.html
실행
정적 컨텐츠 이미지
조금 동적으로 변경하여 올림.
정적과 차이) 파일을 그대로 전달 vs 서버에서 변형(html)해서 내리는 방식
Controller
@Controller
public class HelloController {
@GetMapping("hello-mvc")
public String helloMvc(@RepuestParam("name") String name, Model model) {
model.addAttribute("name", name);
return "hello-template";
}
}
View
<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>
{$name}이므로 해당하는 모델의 key값(이 경우 name)을 가져와서 띄워줌.
MVC, 템플릿 엔진 이미지
(위 이미지와는 다르게 변경해서 넘어감.)
JSON 데이터 포맷으로 클라이언트에게 전달하는 방식.
1. view 나 react에서도 api로 내려서 화면은 클라이언트가 그리도록 할때 사용
2. 서버끼리 통신할때
@ResponseBody 문자 반환
@Controller
public class HelloController {
@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name) {
return "hello"+name;
}
}
@ResponseBody
를 사용하면 뷰 리졸버(viewResolver
)를 사용하지 않음실행
@ResponseBody 객체 반환
@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;
}
}
실행
@RestponseBody 사용 원리
ResponseBody
를 사용viewResolver
대신에 HttpMessageConverter
가 동작StringHttpMessageConverter
MappingJackson2HttpMessageConverter
참고: 클라이언트의 HTTP Accept 해더와 서버의 컨트롤러 반환 타입 정보 둘을 조합해서
HttpmessageConverter
가 선택된다. 더 자세한 내용은 스프링 MVC 참조.