source

스프링 부트 HTML 및 JavaScript 추가

factcode 2023. 4. 4. 22:29
반응형

스프링 부트 HTML 및 JavaScript 추가

HTML5와 JavaScript를 사용하여 Spring 부팅 앱을 실행하려고 하는데 문제가 있습니다.

프로젝트 구조는 다음과 같습니다.

여기에 이미지 설명 입력

Spring MVC 컨트롤러가 offer.html 파일을 호출하고 있는데 정상적으로 작동합니다.

제 오퍼.html 파일은 다음과 같습니다.

<!DOCTYPE html>
<html lang="en" ng-app="coByTu">
<head>
    <title>Page</title>
    <script type="text/javascript" src="../js/lib/angular.js" />
    <script type="text/javascript" src="../js/src/offer.js" />
</head>
<body>

</body>
</html>

또한 앱 URL http://localhost:8080/offerView를 입력할 때

서버로부터의 응답:

여기에 이미지 설명 입력

왜 앱이 이 스크립트 파일을 볼 수 없는지 모르겠습니다만, 제가 무엇을 잘못했는지 알 수 있는 사람이 있습니까?

기본적으로 javascript 파일 등 정적으로 서비스해야 하는 모든 콘텐츠는 정적인 폴더 아래에 배치해야 합니다.https://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot

https://github.com/ericbv/staticContentWithSpringBoot의 간단한 작업 예를 정리했습니다.

파일 구조:

HTML 파일:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Page</title>
    <script type="text/javascript" th:src="@{/js/lib/angular.js}" />
    <script type="text/javascript" th:src="@{/js/src/offer.js}" />
</head>
<body>

th:src를 사용하면 링크가 컨텍스트를 인식하고 있는지 확인합니다.

Edit: 참조 컨텍스트를 인식하도록 th:src를 추가했습니다.

같은 이슈의 이 페이지를 찾는 사람에게만요.스크립트가 실행되지 않음' 문제를 해결하는 방법은 매우 간단했습니다.

간단하게 치환:

<script type="text/javascript" src="js/src/Test.js" />

와 함께

<script type="text/javascript" src="js/src/Test.js" ></script>

(테스트는 'static/js/src'에 있습니다)나 이외의 사용자에게 도움이 되었으면 합니다.

건배.

정적 js 파일을 정적 폴더에 넣어야 합니다.자세한 것은, https://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot 를 참조해 주세요.

js 디렉토리(및 내용)를 (템플릿에 있는 것이 아니라) 정적 디렉토리로 옮겨야 한다고 생각합니다.

를 사용하여 웹 컨텍스트에서 정적 파일을 처리하는 데 사용할 문서 루트 디렉토리를 설정합니다.

작업 예:

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:static-assets-folder: myfolder):

> java -jar demo-0.0.1-SNAPSHOT.jar --static-assets-folder="myfolder"
> java -jar demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=myprofile

Spring Boot 초보자에게도 같은 문제가 있었습니다.html 문서 하단에 있는 <스크립트> 태그(타일 리프 템플릿)에서는 jQuery 코드가 정상적으로 동작하고 있었습니다만, static/js 폴더의 외부 .js 문서에 동일한 코드를 넣어도 응답이 없습니다.매우 간단한 수정 - 이 안에 .js 문서 코드를 모두 넣으면 됩니다.$ ( document ) 。ready ( function ) {...code...})그리고 정상적으로 동작했습니다.이게 도움이 됐으면 좋겠네요.

는 ㅇㅇㅇㅇㅇㅇㅇㅇ다를 넣었습니다.spring.mvc.static-path-pattern=/static/**하고 있습니다.application.properties로 이행합니다.

씁니다.src="/static/js/jQuery.min.js"

언급URL : https://stackoverflow.com/questions/33925712/spring-boot-add-html-and-javascript

반응형