[Spring]View 환경설정
[모든 포스팅은 개인적 공부를 위해 작성된 글입니다]
<Welcome Page>
- 도메인만 입력해서 들어오는 경우 표시되는 페이지
- src/main/resources/static/index.html
- 정적 페이지
<thymeleaf 템플릿 엔진>
- 템플릿 엔진을 사용하면 동적페이지 만들 수 있음
<Controller>
- 웹 애플리케이션의 첫번째 진입점
- 사용자가 화면(View)에서 입력 또는 이벤트 발생시켰을 경우 그에 맞는 화면이나 비즈니스 로직(Model) 실행할 수 있도록 업데이트 해주는 역할 담당
- 컨트롤러의 역할
- 1. Data receive
- 2. Interpret
- 3. Validate input data
- 4. Update View
- 5. Modify Model
- 단순히 말해서 컨트롤러는 Model와 View를 이어주는 다리 역할이라고 보면 됨
- @Controller 어노테이션 붙여줘야 함(해당 클래스가 컨트롤러임을 나타내고 자동으로 bean 이 등록되어 해당 클래스를 컨트롤러로 사용할 수 있음)
- hello.hellospring 패키지에 controller 패키지 생성 후 HelloController 클래스 생성
@Controller
public class HelloController {
@GetMapping("hello")
public String hello(Model model){
model.addAttribute("data", "hello!!");
return "hello";
}
}
- 이와같이 Controller 어노테이션을 적어줘야 함
- @GetMapping("hello")
- 주소창에 localhost:8080/hello 입력하는 경우 hello 메서드 호출되도록 매핑
- 웹 브라우저에서 주소창에 /hello가 입력되면 톰캣이 컨트롤러에 가서 "hello"로 매핑되어 있는 클래스(여기서는 hello)를 실행시킴(hello가 실행됨) -> 여기서 매개변수가 model 이므로 spring이 model 만들어서 넣어줌 -> 여기서 addAttribute(키, 값);으로 값을 넣어줌 -> return "hello";는 src/main/resources/templates에 있는 hello.html을 의미 -> return "hello";는templates에 있는 hello.html을 찾아서 해당 파일을 실행시켜라는 뜻
- 즉, 간단히 말하자면 컨트롤러에서 리턴 값으로 문자를 반환하면 뷰 리졸버(viewResolver)가 화면을 찾아서 처리함
- 여기서 스프링 부트 템플릿엔진 기본 viewName 매핑이 resources:templates/+{viewName}+.html
- 이로 인해 templates의 hello.html이 실행되는 것
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org"> <!-- thymeleaf 문법 쓸 수 있도록 함-->
<head>
<title>Hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<p th:text="'안녕하세요. ' + ${data}">안녕하세요. 손님</p> <!-- HelloController에서 Model의 attribute로 넣은 data 의미 -> 여기에서는 hello!!가 들어감-->
</body>
</html>
- templates의 hello.html
- ${data}의 data는 model로부터 넘겨받은 키의 값
- th는 thymeleaf의 문법
- th:text -> 태그 안의 텍스트를 서버에서 전달 받은 값에 따라 표현할 때 사용
<참고>
[무료] 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술 - 인프런 | 강의
스프링 입문자가 예제를 만들어가면서 스프링 웹 애플리케이션 개발 전반을 빠르게 학습할 수 있습니다., - 강의 소개 | 인프런
www.inflearn.com
https://yongku.tistory.com/2348
스프링(Spring) 프레임워크 Controller란?
츄르사려고 코딩하는집사입니다. 스프링 프레임워크(Spring Framework)의 MVC 패턴 스프링 프레임워크(Spring Framework)에서는 MVC(Model - View - Controller) 패턴을 사용하고 있습니다. MVC(Model - View - Controller)
yongku.tistory.com