Spring으로 웹 개발시 크게 정적 콘텐츠, MVC와 템플릿 엔진, API 3가지 방식이 있다.
서버에서 별다른 작업이 이루어지지 않고, html 파일을 그대로 넘겨줘서 보여주는 방식이다.
클라이언트가 http://localhost:8080/hello-mvc?name=spring으로으로 접속하는 경우, 내장 톰켓 서버을 통해서 스프링은 controller 메서드를 호출한다.
controller는 hello-template, model(name:spring)을 스프링에게 보낸다.
@Controller
public class HelloController{
//hello-mvc라는 url에 매칭이 되도록 한다.
@GetMapping("hello-mvc")
public String helloMvc(@RequestParam("name") String name, Model model){
model.addAttribute("name", name);
return "hello-template";
}
viewResolver는 view를 찾아주고, template engine(thymeleaf)를 찾아준다.
viewResolver가 templates에서 hello-template을 찾아서 Thymeleaf 템플릿 엔진에게 보낸다.
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>
@Controller
public class HelloController{
@GetMapping("hello-string")
@ResponseBdoy
public String helloString(@RequestParam("name") String name){
return "hello " + name;
}
}
@Controller
public class HelloController{
@GetMapping("hello-api")
@ReponseBody //Json으로 반환한다.
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){
his.name = name;
다음 글은 인프런 김영한 강사님의 스프링 강의 복습용입니다 :)