Spring02 스프링 웹 개발 기초
스프링 웹 개발 기초
- 정적 컨텐츠 : 파일을 그대로 전달
- MVC와 템플릿 엔진 : 서버에서 변형을 해서 전달
- API : 제이슨 파일로 데이터를 전달
정적 컨텐츠
- 스프링 부트의 정적 컨텐츠 기능
- https://docs.spring.io/spring-boot/docs/2.3.7.RELEASE/reference/html/spring-boot-features.html#boot-features-spring-mvc-static-content
<!DOCTYPE HTML>
<html>
<head>
<title>static content</title>
<meta http-equive="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
정적 컨텐츠입니다.
</body>
</html>
- 실행 : http://localhost:8080/hello-static-html
- 정적 컨텐츠 이미지

MVC와 템플릿 엔진
-
MVC : Model, View, Controller
-
Controller
@Controller
public class HelloController {
@GetMapping("hello-mvc")
public String helloMvc(@RequestParam("name") 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>
- 실행 : http://localhost:8080/hello-mvc?name=spring
- MVC, 템플릿 엔진 이미지

API
- @ResponseBody 문자 반환
@Controller
public class HelloController {
@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name) {
return "hello" + name;
}
}
- @ResponseBody를 사용하면 뷰 리졸버를 사용하지 않음
- 대신에 HTTP의 BODY에 문자 내용을 직접 반환(HTML BODY TAG를 말하는 것이 아님)
-
실행 : http://localhost:8080/hello-string?name=spring
- @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;
}
static class Hello {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
- @ResponseBody 사용 원리

- @ResponseBody를 사용
- HTTP의 BODY에 문자 내용을 직접 반환
- 뷰 리졸버 대신에 HttpMessageConverter가 동작
- 기본 문자처리 : StringHttpMessageConverter
- 기본 객체처리 : MappingJackson2HttpMessageConverter
- Jackson : 객체를 제이슨으로 바꿔주는 라이브러리 (잭슨과 Gson이 있음)
- Byte 처리 등등 기타 여러 HttpMessageConverter가 기본으로 등록되어 있음