html을 동적으로 바꾸어서
내려주는 것정적 컨텐츠
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>
실행: http://localhost:8080/hello-static.html
MVC와 템플릿 엔진
Model, View, Controller
model
에 화면에 필요한 것들 담아서 화면으로 넘김@Controller
public class HelloController {
@GetMapping("hello-mvc")
public String helloMvc(@RequestParam("name") String name, Model model) {
model.addAttribute("name", name);
return "hello-template";
}
}
@RequestParam("name")
resources/template/hello-template.html
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>
<p th:text="'hello ' + ${name}">hello! empty</p>
: th:text="'hello ' + ${name}
" 안의 값으로 hello! empty
가 치환됨hello! empty
: 서버 없이 html을 만들어서 볼 때실행: http://localhost:8080/hello-mvc?name=spring!
HelloController
에서 매핑을 찾아 메소드 호출API
@Controller
public class HelloController {
@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name) {
return "hello" + name;
}
}
@ResponseBody
@ResponseBody
를 사용하면 뷰 리졸버(viewResolver
)를 사용하지 않음 == view가 없음실행 : http://localhost:8080/hello-string?name=spring!!!
결과: hello spring!!!
페이지 소스에도 hello spring!!!만 있음
@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;
}
}
}
내부 클래스는 static으로 선언해야 함
참고: Java의 내부 클래스는 static으로 선언하자
실행: http://localhost:8080/hello-api?name=spring??
결과: JSON (key-value로 이루어진 데이터 포맷)
{"name":"spring!!!"}
페이지 소스도 똑같이 {"name":"spring!!!"}
@ResponseBody
가 있으면 HTTP의 BODY에 문자 내용을 직접 반환viewResolver
대신에 HttpMessageConverter
가 동작StringHttpMessageConverter
MappingJackson2HttpMessageConverter
byte 처리 등등 기타 여러 HttpMessageConverter가 기본으로 등록되어 있다.
참고: 클라이언트의 HTTP Accept 헤더와 서버의 컨트롤러 반환 타입 정보 둘을 조합해서
HttpMessageConverter
가 선택된다. 더 자세한 내용은 스프링 MVC 강의에서 설명하겠다.