
스프링은 기본적으로 정적컨텐츠를 제공한다.
- ' /resource/static/ '에 html 파일을 만든 후 서버를 켜고 'localhost:8080/<html파일명.html>' 으로 들어가면 자동적으로 연결된다.
- 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"; } }
- View -> 화면을 그리는데 모든 것을 집중하는 부분
resources/templates/hello-template.html<html xmlns:th="http://www.thymeleaf.org"> <body> <p th:text="'hello ' + ${name}">hello! empty</p> </body> </html>
- Response body : http 통신 프로토콜의 응답 body부에 넣어주겠다는 의미
- 템플릿 없이 그대로 데이터를 내려준다
- ResponseBody 문자 반환
@Controller public class HelloController { @GetMapping("hello-string") @ResponseBody // 이것을 사용하면 viewResolver가 필요하지 않음 public String helloString(@RequestParam("name") String name) { return "hello " + name; } }
- ResponseBody 객체 반환 -> 객체 반환 시 json 형태로 변환된다.
@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; } } }
viewresolver 대신에 HttpMessageConverter가 동작한다.