서버를 거치지 않고 파일을 웹 브라우저에 그대로 내려주는 것
예시를 들어봅시다.
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 로 접속하면 다음과 같은 결과가 나옵니다.
static 폴더에 원하는 파일을 넣으면 정적 파일로 반환됩니다.
하지만 이 파일에 그 어떤 프로그래밍도 할 수 없습니다.
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";
}
}
resources/template/hello-template.html
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body></html>
이렇게 코드를 작성한 후 실행해보면 다음과 같이 나옵니다.
@RequestParam의 name을 통해 Model이 담겨지기 때문입니다.
thymeleaf 템플릿은 주소창에 파일 경로로 이동해도 그대로 결과가 나옵니다.
MVC, 템플릿 엔진 동작 과정
viewResolver
@ResponseBody 문자 반환
@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name) {
return "hello " + name;
}
@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;
}
}
}
객체로 넘겨주었다면 디폴트로 JSON 형식으로 만들어서 HTTP에 반환합니다.
학습중인 스프링 강의 : https://inf.run/pcut
스프링 실습 코드 저장소 : https://github.com/0pyaq0/Spring_Study.git
본 글은 2022년도에 작성한 기존 티스토리 블로그 글을 재업로드한 글입니다
기존 티스토리 블로그 : https://develop-about-leejin.tistory.com/