resources/static/ 아래에 html 파일을 넣게되면 정적 페이지를 전달할 수 있음
스프링 컨테이너 내부에 관련된 컨트롤러가 없으면 내장 톰캣 서버에서
resources/static/ 에서 관련 파일을 찾아 화면을 보여줌
@Controller
public class HelloController {
@GetMapping("hello-mvc")
public String helloMvc(@RequestParam("name") String name, Model model) {
model.addAttribute("name", name);
return "hello-template";
}
}
컨트롤러에서 @GetMapping을 통해 "hello-mvc"를 URL 경로에 매핑시킨다
이후 @RequestParam("name") String name 에서 URL에 있는 "name"에 들어있는 값을 name에 바인딩한다.
model은 바인딩된 name이란 값을 "name"에 저장한다.
마지막으로 리소스에 있는 hello-template.html를 호출
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}"></p>
</body>
</html>
hello-template.html에선 전달받은 model의 name을 출력하게 된다.
따라서 http://localhost:8080/hello-mvc?name=spring에서 주어지는
name = 뒤에 오는 것이 Param("name")에 들어오는 값이 되고 hello + 입력값의 형태로 출력되는 것이다.
API란?
Application Programming Interface의 줄임말이다.
Application은 고유한 기능을 가진 소프트웨어이고 Interface는 Appliaction간의 서비스 계약이라고할 수 있다. 이 계약은 요청과 응답을 사용하여 두 애플리케이션이 서로 통신하는 방법을 정의한다.
@GetMapping("hello-api")
@ResponseBody //json으로 반환하는게 기본
public Hello helloapi(@RequestParam("name") String name){
Hello hello = new Hello();
hello.setName(name);
return hello;
}
static class Hello {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
그래서 위의 코드를 보면 아까 위에서 했던 것과 크게 다르지 않지만,
@ResponseBody를 추가함으로서 http의 body에 문자 내용을 직접 반환한다.
MVC와 달리 viewResolver를 이용하지 않는데 그 이유는 애플리케이션간의 통신에선 화면 출력(View)기능이 중요하지 않기 때문이다.
JsonConverter는 객체를 처리할 수 있고 StringConverter를 이용해 기본 문자를 처리할 수 있다.
@ResponseBody에서 객체를 반환하게되면 스프링 컨테이너에서 객체를 처리하는 JsonConverter에 의해 Json형태로 전달된다.