1. 정적 컨텐츠(
index.html
,css
)
: 서버에서 따로 조정할 필요 없이 파일→웹 브라우저를 그대로 '내려준다'.
2. MVC와 템플릿 엔진(jsp
,php
)
: html을 동적으로 서버에서 프로그래밍한 후, 웹 브라우저에 그대로 '내려준다'.
:Model, View, Controller
의 패턴으로 개발한다.
3. API
:json
이라는 데이터 구조 포맷으로 클라이언트에게 전달하는 방식
: 서버끼리의 데이터 호출
resources/static/hello-static.html
파일을 생성하여 시험 가능<!DOCTYPE HTML>
<html>
<head>
<title>static content</title>
<meta http-equiv="Content-Type" content="text.html; charset=UTF-8" />
</head>
<body>
정적 컨텐츠입니다.
</body>
</html>
localhost::8080/hello-static.html
웹 브라우저로 접속하여 확인 가능
- MVC 방식은 결국 View라는 템플릿을 찾아서, 템플릿 엔진을 통하여 화면을 렌더링한 후 html을 웹 브라우저에게 넘겨주는 방식 이다.
@Controller
public class HelloController{
@GetMapping("hello")
public String hello(Model model) {
model.addAttribute("data", "spring!!");
return "hello";
}
@GetMapping("hello-mvc")
public String helloMvc(@RequestParam("name") String name, Model model) {
//외부에서 받아온 파라미터
model.addAttribute("name", name);
return "hello-template"; //hello-template가 반환값
}
@RequestParam(value= "name", required = "...")
에서 required의 default값이 true이므로, 기본적으로 값을 넘겨야 한다.
resources/templates/hello-template.html
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'안녕하세요. '+ ${name}">hello! empty</p>
</body>
</html>
localhost:8080/hello-mvc?name=spring!
에서 파라미터인 spring!값을 넘기면, Controller에서 name자리에 spring!이 들어가 model.attribute("name", name)에 의하여, model에 담긴다.
model에 담긴 spring!은 View자리로 넘어가 ${name}에 파라미터값을 전달받는다.
@ResponseBody
문자 반환@ResponseBody
를 사용하면 뷰 리졸버(viewResolver
) 대신에, HttpMessageConverter
가 동작한다.MappingJackson2HttpMessageConverter
가 json으로 처리하고 문자면 StringHttpMessageConverter
가 동작한다.HttpMessageConverter
가 기본으로 등록되어있다.@Controller
public class HelloController{
@GetMapping("hello")
public String hello(Model model) {
model.addAttribute("data", "spring!!");
return "hello";
}
@GetMapping("hello-mvc")
public String helloMvc(@RequestParam("name") String name, Model model) {
//외부에서 받아온 파라미터
model.addAttribute("name", name);
return "hello-template"; //hello-template가 반한값
}
@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name) {
return "hello "+name;
}
}
@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;
}
}
여기서 잘 살펴보면 return hello;
부분에서 처음으로 문자가 아닌 객체를 넘겼다. 이 경우 어떻게 될까?
이를 json
방식이라고 한다. {key: value}
구조로 이루어져있다.
과거에는 xml 방식으로 많이 쓰였으나(html을 열고 닫는), 아주 심플한 방식인 json 방식으로 채택이 되고 있다.
- 객체를 반환하고,
@ResponseBody
어노테이션 붙이기