Spring
Gradle-Spring Project #2 - 정적 컨텐츠, MVC-템플릿, API
˙ᵕ˙
2020. 10. 4. 16:47
정적 컨텐츠
- html 그대로 서버로 전달 -> 웹 페이지에 보여진다.
- docs.spring.io/spring-boot/docs/2.3.1.RELEASE/reference/html/spring-boot-features.html#boot-features-spring-mvc-static-content
Spring Boot Features
Graceful shutdown is supported with all four embedded web servers (Jetty, Reactor Netty, Tomcat, and Undertow) and with both reactive and Servlet-based web applications. It occurs as part of closing the application context and is performed in the earliest
docs.spring.io
- 스프링은 resources/static 폴더 아래에 있는 페이지를 찾아 정적 페이지로 보여준다.
<!DOCTYPE HTML>
<html>
<head>
<title>static content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
정적 컨텐츠 입니다.
</body>
</html>
- 실행
- 파일명 그대로 접속할 수 있다.
- 스프링은 hello-static으로 요청이 들어오면 우선 관련 컨트롤러가 있는지 찾고, 없으면 정적 컨텐츠를 찾는다.
MVC와 템플릿 엔진
- MVC : Model, View, Controller
Controller
@Controller
public class HelloController {
@GetMapping("hello-mvc")
public String helloMvc(String name, Model model) {
model.addAttribute("name", name);
return "hello-template";
}
}
View
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>
- 실행
- 컨트롤러에서 name 파라미터를 받아서 사용하고 있으므로 get방식으로 parameter를 넘겨준다
- hello-mvc?name=spring!!! 으로 요청이 들어온다
- 서버를 통해 컨트롤러에 전달
- 넘어온 name 파라미터를 받아서 처리 후 viewResolver 로 전달
- viewResolver는 view와 controller를 연결 해 준다.
- 넘어온 값들을 변환(Thymeleaf 템플릿 엔진 처리)해서 웹브라우저로 response
@Controller
public class HelloController {
@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name) {
return "hello " + name;
}
}
API
- @ResponseBody
- ViewResolver를 사용하지 않는다
- return된 문자열 그대로 반환
- 실행
- @ResponseBody 객체 반환하기( 기본 json으로 반환 )
@Controller
public class HelloController {
@GetMapping("hello-api")
@ResponseBody
public Hello helloApi(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;
}
}
}
- 실행
- json 객체로 반환
- hello-api 요청
- 서버를 통해 컨트롤러에 전달
- @ResponseBody 어노테이션이 있으면 ViewResolver 대신 HttpMessageConverter로 전달
- < HttpMessageConverter >
- 기본 문자처리: StringHttpMessageConverter
- 기본 객체처리: MappingJackson2HttpMessageConverter
- byte 처리 등등 기타 여러 HttpMessageConverter가 기본으로 등록되어 있음
- 웹으로 전달