1. 동적페이지 (resources/templates)
// http://localhost:8080/hello
@Controller
public class HelloController {
@GetMapping("hello")
public String hello(Model model) {
model.addAttribute("data", "hello!!");
return "hello";
}
}
1. 사용자가 Request시, 내장 Tomcat이 스프링 컨테이너에서 hello가 Mapping 되어 있는 Controller를 찾는다. -> 있음
2. mapping되어 있는 함수 호출 후, Return 처리
3. Return이 문자열인 경우, ViewResolver를 통해 resources/templates/에서 해당. html파일을 찾아서 Response 처리
Q. hello가 Mapping되어 있는 Controller가 여러 개라면? 어떻게 찾는지? 우선순위가 있는지?
> 동일 GetMapping이 존재하는 경우 : Ambiguous mapping. Cannot map method 오류 발생
> GetMapping("hello"), PostMapping("hello")는 가능하지만, GetMapping("hello")는 1개만 존재 가능
2. 정적페이지 (resources/static)
<!-- http://localhost:8080/hello-test.html -->
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'안녕하세요. ' + ${data}" >안녕하세요. 손님</p>
</body>
</html>
1. 사용자가 Request시, 내장 Tomcat이 스프링 컨테이너에서 hello-test가 Mapping 되어 있는 Controller를 찾는다. -> 없음.
2. resources/static/에서 해당 .html파일을 찾아서 Response 처리
-> 정적 페이지 이므로, Rendering하지 않고 html파일 그대로 표시
3. ResponseBody(1)
@Controller
public class HelloController {
@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name) {
return "hello " + name;
}
}
1. 사용자가 Request시, 내장 Tomcat이 스프링 컨테이너에서 hello-test가 Mapping 되어 있는 Controller를 찾는다. -> 있음
2. @ReponseBody가 있고, return이 String인 경우 HttpMessageConverter(StringHttpMessageConverter)로 처리
3. return값 HTTP Body로 Response 처리
4. ResponseBody(2)
@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;
}
}
}
1. 사용자가 Request시, 내장 Tomcat이 스프링 컨테이너에서 hello-test가 Mapping되어 있는 Controller를 찾는다. -> 있음
2. @ReponseBody가 있고, return이 객체인 경우 HttpMessageConverter(MappingJackson2HttpMessageConverter)로 처리
3. return값 HTTP Body로 Response 처리
CASE 정리
해당 내용은 "인프런" - "스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술"을 학습하며 정리한 내용입니다.
틀린 사항이 있을 경우, 알려주시면 감사하겠습니다 :)
'개발 > Spring' 카테고리의 다른 글
스프링Bean과 의존성 주입(DI) (0) | 2023.01.17 |
---|---|
Spring Boot에서 JUnit 사용 (0) | 2023.01.17 |