김영현님의 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술을 수강하면서 기록하는 노트 ✍️
스프링 부트는 정적 컨텐츠를 자동으로 지원해준다.
파일을 만들고 프로젝트를 실행 시킨다.
이렇게 패스에 파일명만 적어도 자동으로 반환이 된다!
하지만 정적 파일에는 어떤 프로그래밍을 할 수는 없다.
현 패스로 요청이 들어오면 스프링 부트는 먼저 controller에서 해당 파일을 찾고,
없다면 resources:statc/hello-static을 찾아 반환한다.
...
@GetMapping("hello-mvc")
public String helloMvc(@RequestParam(value = "name",required = true) String name, Model model){
model.addAttribute("name",name);
return "hello-template";
}
"hello-mvc"패스로 요청이 오면, "hello-template" 파일을 반환한다.
RequestParam으로 파라미터를 전달한다.
(@RequestParam(value = "name",required = true)
필수이며, name을 파라미터로 전달한다.
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'안녕하세요. ' +${name}">helo! empty</p>
</body>
</html>
ResponseBody 객체의 반환
정적 컨텐츠를 제외하면 HTML로 내리냐, API로 데이터를 내리냐로 나뉜다.
@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name){
return "hello " + name;
}
@ResponseBody의 활용
static class를 쓰면 class안에서 클래스 사용 가능.
...
@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;
// getter와 setter은 java bean 표준 방식이다. (프로퍼티 접근 방식)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
이렇게 json 형식으로 나온다!
객체가 오면 json으로 만들어 반환하는 것이 기본 정책!