정적 컨텐츠는 파일을 그대로 웹 브라우저에 내려주는 것이다.
스프링부트는 정적 컨텐츠 기능을 기본으로 제공한다.
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>
resorces/static 위치에 html 파일 작성 후 웹 브라우저에서 /파일명 으로 접속하면 해당 html 파일이 뜬다.
서버에서 프로그래밍해서 html을 동적으로 바꾼 후 내리는 방식이다.
정적 컨텐츠는 파일을 그대로 전달해주었다면, MVC와 템플릿 엔진은 서버에서 변형하여 전달한다.
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
resources/templates/hello-template.html
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
이렇게 작성하고 웹 브라우저에서 localhost:8080/hello-mvc 로 접속하면 hello-template.html 페이지가 뜰 것 같지만 다음 메세지와 함께 WARN이 뜬다.
WARN 4930 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required request parameter 'name' for method parameter type String is not present]
controller의 @RequestRaram에서 command+p 단축키를 눌러보면 옵션이 뜨는데 required() 의 default가 true이므로 값을 넘겨주어야 한다.
localhost:8080/hello-mvc?name=spring
이렇게 접속하면 html이 제대로 뜬다.
@ResponseBody 문자 반환
@Controller
public class HelloController {
@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name) {
return "hello " + name;
}
}
실행
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를 사용