YUIN

View 환경설정 본문

Spring/Spring <입문>

View 환경설정

유_인 2023. 4. 5. 14:07

resources/static/index.html

1. index.html이라는 새로운 파일을 생성한다.

<!DOCTYPE HTML>
<html>
<head>
 <title>Hello</title>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
Hello
<a href="/hello">hello</a>
</body>
</html>

 

2. 위의 코드를 복사 붙여넣기 한다.

 정상 작동을 위해 실행 후 정지를 한 다음에 다시 실행해야 한다.

localhost:8080에 접속하면

welcome page가 정상적으로 작동하는 것을 확인할 수 있다.

물론 hello를 클릭하면 에러가 뜬다. 

 

3. WelcomPage 작동 방식

: SpringBoot 에 의하면 먼저 static content location에 위치해 있는 index.html을 먼저 찾고, 찾아도 없으면 index template을 찾는다고 한다. 둘 중 하나라도 발견되면 자동적으로 어플리케이션의 welcome page로 활용된다. 

 

4. thymeleaf 템플릿 엔진

 

5. Controller

Controller 만들기

hello.hellosping 패키지 아래 controller 패키지를 생성한다. 

만든 controller 패키지 아래 HelloController class를 생성한다. 

>src>main>java>hello.hellospring>controller>HelloController

 

@Controller
public class HelloController {
 @GetMapping("hello")
 public String hello(Model model) {
 model.addAttribute("data", "hello!!");
 return "hello";
 }
}

//Controller annotation을 통해 해당 class가 컨트롤러라는 것을 스프링 부트에게 알려준다. 

//GetMapping을 통해 http://localhost:8080/hello 로 오는 요청을 HelloController 메소드에게 매핑을 해준다.

생성한 class에 위와 같이 입력해주고 

 

resources/templates/hello.html

해당 경로에 따라 hello.html 페이지를 만들어준 뒤

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
 <title>Hello</title>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'안녕하세요. ' + ${data}" >안녕하세요. 손님</p>
</body>
</html>

위의 코드를 입력해주면 

hello를 눌렀을 때 404 에러가 뜬 아까와는 달리

이와 같은 메세지가 뜬다. 

동작 과정을 설명하자면 컨트롤러 코드에서의 return 값(=hello)를 viewResolver가 화면을 찾아서 처리한다. 즉 viewName과 매핑돼 있는 페이지를 찾는 것이라고 이해하면 된다. 우리가 만든 html 페이지 중에선 resources:templates/hello.html이 된다.

 

'Spring > Spring <입문>' 카테고리의 다른 글

API  (0) 2023.04.10
MVC와 템플릿 엔진  (0) 2023.04.08
정적 컨텐츠  (0) 2023.04.08
스프링 웹 개발 기초  (0) 2023.04.08
프로젝트 환경설정  (0) 2023.04.05