728x90
4.2 기본 페이지 만들기
먼저 스프링 부트 프로젝트에서 머스테치를 편하게 사용할 수 있도록 머스테치 스타터 의존성을 build.gradle에 등록
compile('org.springframework.boot:spring-boot-starter-mustache')
머스테치 : 스프링 부트에서 공식 지원하는 템플릿 엔진이다.
머스테치 파일 위치는 기본적으로 위의 위치에 둔다.
-> 스프링 부트에서 자동으로 로딩함.
첫 페이지를 담당할 index.mustache를 templates 폴더를 생성해 넣어두기
index.mustache
<!DOCTYPE HTML>
<html>
<head>
<title>스프링 부트 웹서비스</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
</head>
<body>
<h1>스프링 부트로 시작하는 웹 서비스</h1>
</body>
</html>
이 머스테치에 URL을 매핑. URL 매핑은 당연하게 Controller에서 진행
-> web 패키지 안에 IndexController를 생성함
IndexController
package com.jojoldu.book.springboot.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class IndexController {
@GetMapping("/")
public String index(){
return "index";
}
}
머스테치 스타터 덕분에 컨트롤러에서 문자열을 반환할 때 앞의 경로와 뒤의 파일 확장자는 자동으로 지정.
즉, 여기선 "index"을 반환하므로, src/main/resources/templates/index.mustache로 전환되어 View Resolver가 처리
Test 해보기
IndexControllerTest
package com.jojoldu.book.springboot.web;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment =RANDOM_PORT)
public class IndexControllerTest {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void 메인페이지_로딩(){
//when
String body=this.restTemplate.getForObject("/",String.class);
//then
assertThat(body).contains("스프링 부트로 시작하는 웹 서비스");
}
}
🔊 index.mustache에 "스프링 부트로 시작하는 웹 서비스"가 포함되어 있는지 비교
실제로 화면이 잘 나오는지 확인하기 위해 Application.java를 실행하고 웹브라우저에서 http://localhost:8080으로 접속
출처 : 스프링 부트와 AWS로 혼자 구현하는 웹 서비스 [이동욱 지음]
'Back-End > Springboot와 AWS로 혼자 구현하는 웹 서비스' 카테고리의 다른 글
Chapter 04. 머스테치로 화면 구성하기 (4) (0) | 2022.03.16 |
---|---|
Chapter 04. 머스테치로 화면 구성하기 (3) (0) | 2022.03.15 |
Chapter 04. 머스테치로 화면 구성하기 (1) (0) | 2022.03.15 |
Chapter 03. SpringBoot에서 JPA로 데이터베이스 다뤄보자 (5) (0) | 2022.03.14 |
Chapter 03. SpringBoot에서 JPA로 데이터베이스 다뤄보자 (4) (1) | 2022.03.13 |