정적 페이지 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello Spring</title>
</head>
<body>
Hello, Spring 정적 웹 페이지!! (static)
</body>
</html>
Controller 생성 ( static폴더에 있는 html파일에 접근하는 방법 )
- thymeleaf가 걸려있지 않은 상황에서
- http://localhost:8080/hello.html로 직접접근
- http://localhost:8080/static-hello로 controller를 타고 찾아서 접근
- thymeleaf가 있는 상황에서
- http://localhost:8080/hello.html로 직접접근
↓ thymeleaf가 걸려있지 않은 상황
중요! html(정적 페이지)은 이미 변화가 일어나지 않기 때문에, 굳이 controller를 거칠 필요가 없음!
= thymeleaf 이용하여 controller를 타지말자!
↓ thymeleaf가 걸린 상황
thymeleaf
- 자바 기반의 템플릿 엔진, HTML, XML, JavaScript, CSS 등의 뷰(View) 파일을 동적으로 렌더링하는 데 사용
- 서버사이드에서 데이터를 가공하여 동적으로 HTML을 생성하는 역할
- 사용 방법) build.gradle - dependencies에 implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
1 ) 직접 접근하는 방법
thymeleaf를 이용하면, 이전처럼 /static-hello로 주소를 쓰면 templetes를 찾을 수 없다는 오류가 뜨는데,
이는 http://localhost:8080/hello.html 로 직접 접근하면 들어갈 수 있음!
2) controller를 타고 접근하는 방법 = redirect 이용하기
(직접 접근하는 경로로 다시 요청하세요 : redirect)
- 사용 이유 1) html파일의 이름이 바뀌는 경우 - 서버내에서만 바꾸면 되니까
- 사용 이유 2) 서버내에서 이동 경로 이름을 알리고 싶지 않은 경우
@GetMapping("/html/redirect")
public String htmlStatic(){
return "redirect:/hello.html";
}
http://localhost:8080/html/redirect 로 주소를 치면!
3) Template engine 에 View 전달
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello Spring</title>
</head>
<body>
Hello, Spring 정적 웹 페이지!! (template)
</body>
</html>
- controller에서 @GetMapping("/html/templates")
- return값을 .html을 제외한 문자열로만 작성해도 자동으로 붙어있다고 생각
- 즉, controller라는 annotation이 달린 class에서 - template에 들어가있는 html을 찾을때는 - html앞에 문자열을 넣기
동적 페이지
- client의 요청을 controller에서 Model로 처리
- Template engine(Thymeleaf)에게 view(html파일), model(view에 적용하는 데이터) 전달
- Template
- View에 Model을 적용 → 동적 웹페이지 생성
- 예 ) 로그인 성공 시, "로그인된 사용자의 Nickname"을 페이지에 추가
- Template engine 종류: 타임리프(Thymeleaf), Groovy, FreeMarker, Jade, JSP 등
- Client(브라우저)에게 View(동적 웹 페이지, HTML)를 전달
template에 hello-visit이라는 html파일 생성
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>Hello Spring</title></head>
<body>
<div>
Hello, Spring 동적 웹 페이지!!
</div>
<div>
(방문자 수: <span th:text="${visits}"></span>)
</div>
</body>
</html>
'Spring > Springboot-Intellij' 카테고리의 다른 글
[SpringBoot] Spring MVC - Jackson, ObjectMapper (0) | 2025.01.30 |
---|---|
[SpringBoot] Spring MVC - 데이터를 Client에 반환하는 방법(JSON), RestController (0) | 2025.01.30 |
[SpringBoot] Spring MVC - 인텔리제이(IntelliJ)를 이용하여 Controller생성, 이해하기 (0) | 2025.01.29 |
[SpringBoot] SPRING MVC, Servlet, DispatcherServlet (0) | 2025.01.28 |
[SpringBoot] Lombok(@) / application.properties(설정변경) (0) | 2025.01.28 |