본문 바로가기
프로젝트/Recipository

[Dev] 22.09.14. index.html 띄우기

by 규글 2022. 9. 14.

index.html 띄우기

어젯밤. 간단히 index page를 띄워놓는 작업을 마무리 한 후 잠에 들어, 오늘부터 본격적으로 개발을 시작하려고 했으나 시작부터 난관에 봉착했다.

 

 우선 여러 사람들의 테스트인 main > resources 하위의 static 과 templates 에 page를 만들어서 띄우는 것이었다. 이 두 folder의 용도 차이는 다음 게시글에서 간단히 작성해두려고 한다.

 

 SpringBoot docs에는 위 이미지와 같이 언급되어 있다. [각주:1] static과 templates에서 모두 welcome page가 될 수 있으며, static에서 우선적으로 확인한다는 말이다.

 

 때문에 server를 실행해보면 작성한 index.html 이 반겨주는 것을 확인할 수 있다.

 

 하지만 다른 페이지를 띄우기 위해 controller를 작성하고, 경로 설정을 해서 페이지를 띄우려고 하였으나, 원하는 페이지를 띄우는 것에 실패했다. 이를 가능하게 하려면 어떻게 해야할까?

 

 

Templates의 html 경로 띄우기

검색 결과 templates의 html file을 정상적으로 loading하기 위한 방법은 다음의 두 가지를 발견할 수 있었다.

  • Configuration class를 만들어 annotation을 붙이고, addResourceHandlers method override
  • thymeleaf 사용

 

1. Configuration

 위 이미지는 WebMvcAutoConfiguration의 inner class WebMvcAutoConfigurationAdapter에 있는 resoureceProperties field의 type에 해당하는 WebProperties class의 inner class로 정의된 Resources에 작성된 내용이다. 이로 인해 기본적으로 SpringBoot는 다음의 네 가지를 static resource로 바라본다. 여기에서 classpath는 src/main/resources/ 를 의미하는 것 같다.

  • classpath:/META-INF/resources/
  • classpath:/resources/
  • classpath:/static/
  • classpath:/public/

 그래서 따로 templates folder 안에 있는 html file을 읽을 수 없었던 것이다. 이는 검색을 해본다면 꽤나 여러 블로그에서 확인할 수 있었다.[각주:2] [각주:3]

 

 그렇다면 어떤 방식으로 이를 해결할 수 있을까?

 

@Configuration
public class MvcConfiguration implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/", "classpath:/templates/")
                .setCacheControl(CacheControl.maxAge(10, TimeUnit.MINUTES));
    }
}

 위 코드처럼 작성해주었을 때, templates의 main.html을 띄울 수 있었다. addResourceHandler의 /** 은 slash / 로 시작하는 모든 요청을 다루겠다는 의미이고, addResourceLocations는 해당 위치에서 resource를 찾겠다는 의미이다.

 

 다만 여기에서 추가적으로 고려했어야 할 사항은 controller에서 html 요청을 할 때 main 이 아닌 main.html을 요청했어야 한다는 점이다. 이전 프로젝트의 습관이 남아 이로 인해 페이지 확인을 할 수 없었다.

 

 그리고 더하여 home을 return 한 경우, circular view path 오류를 발생시켰다. 이는 위와 같이 html 파일을 요청한 것이 아니라 home 이라는 경로를 요청했기 때문일 것이다.

 

 하지만 이런 방식 말고 필자는 thymeleaf 라는 것을 사용해보려고 한다. 이 게시글에서는 단순히 어떤 방식을 취해 해결하는지만 알아보고 thymeleaf에 대해서는 static과 templates 의 차이를 알아본 다음 게시글에서 다뤄볼 생각이다.

 

2. thymeleaf

// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf', version: '2.7.3'

MVN repository[각주:4]에서 thymeleaf 를 찾아 dependency에 추가해주었다.

 

#thymeleaf 참조 경로
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

#thymeleaf에 대한 캐시를 남기지 않는다. cache=false 설정(운영시는 true)
spring.thymeleaf.cache=false
#templates 디렉토리에 파일이 있는지 없는지 체크, 없으면 에러를 발생시킨다.
spring.thymeleaf.check-template-location=true

 그리고 application.properties에 위와 같은 내용을 추가해주었다.[각주:5] 작성한 참조 경로에 대한 내용 덕분에 controller에서는 templates folder를 우선적으로 확인하게 되었으며, html 확장자 또한 작성해주지 않아도 된다.

 

 이렇게 index.html 페이지를 띄워보았다. 조금씩 전진해보겠다.

 

Reference

댓글