Develope Me!

[SpringBoot] 스프링 부트와 AWS로 혼자 구현하는 웹 서비스 - 머스테치 적용 본문

Java/SpringBoot

[SpringBoot] 스프링 부트와 AWS로 혼자 구현하는 웹 서비스 - 머스테치 적용

코잘알지망생 2022. 3. 13. 18:06

코로나 확진되고 격리 해제까지..아주 다사다난했던 일주일이었다..ㅎ

증상이란 증상은 다 겪고 나서 이제 좀 정신을 차렸다.

 

저번 포스팅에선 템플릿엔진이 무엇인지를 알아보고 템플릿엔진인 머스테치 플러그인을 설치해봤다.

이번엔 머스테치를 적용해보고 테스트를 진행하여 잘 적용되었는지를 확인해보고자 한다. 

 

 

build.gradle

implementation('org.springframework.boot:spring-boot-starter-mustache')

머스테치 플러그인을 설치해준 뒤 build.gradle파일에 머스테치 의존성을 추가해준다. 

 

 

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>

src/main/resources/templates에 위치 시키면 머스테치 파일을 스프링 부트가 자동으로 로드해준다. 

 

IndexController

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class IndexController {
    @GetMapping("/")
    public String index(){
        return "index";
    }
}

머스테치에 URL을 매핑 시켜주기 위해서 web 패키지 안에 IndexController를 생성해줬다.

머스테치 스타터를 추가해줬기 때문에 컨트롤러에서 문자열을 반환할 때 앞의 경로(src/main/resources/templates)와 뒤의 파일확장자(.mustache)가 자동으로 지정된다.

즉, index를 반환하게 되는데 src/main/resources/templates/index.mustache로 전환 되어 View Resolver가 처리하게 된다.

*View Resolver: URL 요청의 결과를 전달할 타입과 값을 지정하는 관리자 

 

 

IndexControllerTest

package com.study.duple.springboot.web;

import org.assertj.core.api.Assertions;
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;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class IndexControllerTest {

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void 메인페이지_로딩(){
        //when
        String body = this.restTemplate.getForObject("/",String.class);
        //then
        Assertions.assertThat(body).contains("스프링 부트로 시작하는 웹 서비스");
    }
}

실제로 URL을 호출했을 때 페이지 내용이 제대로 호출되는 지를 확인하기 위해 Test 파일을 생성했다.

TestRestTemplat을 통해 "/"로 호출했을 때 index.mustache에 포한된 코드가 있는 지를 확인했다.

테스트 코드를 수행해보면 정상적으로 코드가 수행되는 것을 확인할 수 있었다. 

이후 실제 화면으로도 잘 나오는 지 확인하기 위해서 Application의 메인 메소드를 실행하여 브라우저의 localhost로 접속해봤다. 

 

화면에 정상적으로 출력되고 있음을 확인했다! 

 

 

Comments