[Spring Boot] aLog Project - 기본 페이지 만들기

김광현·2023년 9월 6일
0

Project - aLog

목록 보기
5/12
post-thumbnail

[Spring Boot] aLog Project - JPA Auditing 사용하기
에 이어서 머스테치를 사용하여 기본 페이지를 구현합니다. 🏆


💻 머스테치

JSP와 같이 HTML을 만들어주는 가장 심플한 템플릿 엔진입니다.


머스테치 장점

  • 문법이 다른 템플릿 엔진보다 심플합니다.
  • 로직 코드를 사용할 수 없어 View의 역할과 서버의 역할이 명확하게 분리됩니다.
  • Mustache.js와 Mustache.java 2가지가 다 있어, 하나의 문법으로 클라이언트/서버 템플릿을 모두 사용 가능합니다.


build.gradle

머스테치를 사용할 수 있도록 머스테치 스타터 의존성을 등록합니다.

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


index.mustache

src/main/resources/templatesindex.mustache를 생성합니다.
✅ 머스테치의 파일 위치는 기본적으로 src/main/resources/templates입니다.

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


IndexController.java

index.mustache에 URL을 매핑하기 위한 IndexContoller.javaController 패키지에 생성합니다.

package com.aLog.controller;

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

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

머스테치 스타터 덕분에 컨트롤러에서 문자열을 반환할 때 앞의 경로와 뒤의 파일 확장자는 자동으로 지정됩니다. 앞의 경로는 src/main/resources/templates로, 뒤의 파일 확장자는 .mustache가 붙는 것입니다.


IndexControllerTest.java

package com.aLog.controller;

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 메인페이지_로딩() {
        String body = this.restTemplate.getForObject("/", String.class);

        assertThat(body).contains("aLog");
    }
}

✔ 머스테치를 이용하여 기본 페이지를 구현해봤습니다.

profile
🅸nterest 🆂olving 🆃horough 🅹udgment

0개의 댓글