복붙노트

[SPRING] Spring Boot Embedded tomcat에서 외부 정적 HTML 파일을 서비스하는 방법은?

SPRING

Spring Boot Embedded tomcat에서 외부 정적 HTML 파일을 서비스하는 방법은?

Spring 프레임 워크와 Spring Boot가 처음이다. 아주 간단한 RESTful Spring Boot 웹 애플리케이션을 구현했다. 거의 모든 소스 코드를 다른 질문으로 볼 수 있습니다 : Spring Boot : JDBC 데이터 소스 설정을 외부화하는 방법?

앱에서 외부 정적 HTML, CSS js 파일을 어떻게 처리 할 수 ​​있습니까? 예를 들어, 디렉토리 구조는 다음과 같습니다.

MyApp\
   MyApp.jar (this is the Spring Boot app that services the static files below)
   static\
       index.htm
       images\
           logo.jpg
       js\
           main.js
           sub.js
       css\
           app.css
       part\
           main.htm
           sub.htm

정적 HTML 파일을 포함하는 .WAR 파일을 작성하는 방법을 읽었지만 단일 HTML 파일 수정시에도 WAR 파일의 재구성 및 재배포가 필요하기 때문에이 방법은 용인 할 수 없습니다.

Spring에 대한 나의 지식은 매우 제한되어 있으므로 정확하고 구체적인 대답이 바람직합니다.

해결법

  1. ==============================

    1.다른 질문에서 볼 수 있듯이 실제로 원하는 것은 응용 프로그램의 정적 리소스에 대한 경로를 기본값에서 변경할 수 있어야한다는 것입니다. 왜 그렇게하고 싶은지 질문을 떠나서 몇 가지 가능한 대답이 있습니다.

    다른 질문에서 볼 수 있듯이 실제로 원하는 것은 응용 프로그램의 정적 리소스에 대한 경로를 기본값에서 변경할 수 있어야한다는 것입니다. 왜 그렇게하고 싶은지 질문을 떠나서 몇 가지 가능한 대답이 있습니다.

  2. ==============================

    2.'-cp'를 지정하면 충분합니다. 'java -jar blabla.jar'명령의 옵션이고 현재 디렉토리의 '정적'디렉토리입니다

    '-cp'를 지정하면 충분합니다. 'java -jar blabla.jar'명령의 옵션이고 현재 디렉토리의 '정적'디렉토리입니다

  3. ==============================

    3.이 Dave Syer의 응답 구현을 살펴보십시오.

    이 Dave Syer의 응답 구현을 살펴보십시오.

    ConfigurableEmbeddedServletContainer.setDocumentRoot (File documentRoot)를 사용하여 정적 파일을 제공하기 위해 웹 컨텍스트에서 사용할 문서 루트 디렉토리를 설정할 수 있습니다.

    실례 :

    package com.example.config;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
    import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
    import org.springframework.boot.web.servlet.ServletContextInitializer;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.core.env.Environment;
    import org.springframework.util.StringUtils;
    
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import java.io.File;
    import java.nio.file.Paths;
    
    @Configuration
    public class WebConfigurer implements ServletContextInitializer, EmbeddedServletContainerCustomizer {
        private final Logger log = LoggerFactory.getLogger(WebConfigurer.class);
    
        private final Environment env;
        private static final String STATIC_ASSETS_FOLDER_PARAM = "static-assets-folder";
        private final String staticAssetsFolderPath;
    
        public WebConfigurer(Environment env, @Value("${" + STATIC_ASSETS_FOLDER_PARAM + ":}") String staticAssetsFolderPath) {
            this.env = env;
            this.staticAssetsFolderPath = staticAssetsFolderPath;
        }
    
        @Override
        public void onStartup(ServletContext servletContext) throws ServletException {
            if (env.getActiveProfiles().length > 0) {
                log.info("Web application configuration, profiles: {}", (Object[]) env.getActiveProfiles());
            }
            log.info(STATIC_ASSETS_FOLDER_PARAM + ": '{}'", staticAssetsFolderPath);
        }
    
        private void customizeDocumentRoot(ConfigurableEmbeddedServletContainer container) {
            if (!StringUtils.isEmpty(staticAssetsFolderPath)) {
                File docRoot;
                if (staticAssetsFolderPath.startsWith(File.separator)) {
                    docRoot = new File(staticAssetsFolderPath);
                } else {
                    final String workPath = Paths.get(".").toUri().normalize().getPath();
                    docRoot = new File(workPath + staticAssetsFolderPath);
                }
                if (docRoot.exists() && docRoot.isDirectory()) {
                    log.info("Custom location is used for static assets, document root folder: {}",
                            docRoot.getAbsolutePath());
                    container.setDocumentRoot(docRoot);
                } else {
                    log.warn("Custom document root folder {} doesn't exist, custom location for static assets was not used.",
                            docRoot.getAbsolutePath());
                }
            }
        }
    
        @Override
        public void customize(ConfigurableEmbeddedServletContainer container) {
            customizeDocumentRoot(container);
        }
    
    }
    

    이제 명령 줄 및 프로필 (src \ main \ resources \ application-myprofile.yml)을 사용하여 응용 프로그램을 사용자 정의 할 수 있습니다.

    > java -jar demo-0.0.1-SNAPSHOT.jar --static-assets-folder="myfolder"
    > java -jar demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=myprofile
    
  4. from https://stackoverflow.com/questions/20064241/how-to-service-external-static-html-files-in-spring-boot-embedded-tomcat by cc-by-sa and MIT license