⭐️ 스프링 컨테이너에서 hello-static에 관련된 컨트롤러를 우선으로 찾는다. 없으면 resources/static에서 hello-static html을 찾아서 웹브라우저로 보낸다.
@Controller
public class HelloController {
@GetMapping("/hello-mvc")
public String helloMvc(@RequestParam(value = "name", required = true) String name, Model model) {
model.addAttribute("name", name);
return "hello-template";
}
}
@RequestParam(value = "name", required = true) String name : URL 쿼리 파라미터로 넣은 값을 받아오기 위해 사용하는 코드이다. ```
resources/template/hello-template.html
<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>
View Template는 컨트롤러가 전달하는 model data를 이용하여 동적으로 화면을 구성할 수 있게 해준다. 뷰 템플릿 중 타임 리프가 있는데, 타임 리프는 html tag를 기반으로 하여 'th:' 속성을 이용하여 동적인 View를 제공하는 템플릿 엔진이다.
@Controller
public class HelloController {
@GetMapping("/hello-string")
@ResponseBody // HTTP의 body 부분에 직접 넣어주겠다는 뜻
public String helloString(@RequestParam("name") String name) {
return "hello" + name;
}
}
@Controller
public class HelloController {
// 데이터를 요구할때 유용하게 사용된다. -> API
@GetMapping("hello-api")
@ResponseBody
public Hello helloApi(@RequestParam("name") String name) {
Hello hello = new Hello();
hello.setName(name);
return hello; // 인스턴스(객체)를 넘긴다. -> JSON 방식으로 출력됨
}
static class Hello {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
result
{"name":"SPRING"}