programing

스프링 부트로 CSS가 로드되지 않음

golfzon 2023. 3. 10. 22:59
반응형

스프링 부트로 CSS가 로드되지 않음

봄 프레임 작업이나 봄 부츠는 처음입니다.CSS,javascript,js에 static html 파일을 추가하려고 합니다.파일 구조는

프로젝트 구조

그리고 내 html 파일 헤드는 이렇게 생겼다.

<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>HeavyIndustry by HTML5Templates.com</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <meta name="description" content="" />
    <meta name="keywords" content="" />

    <link rel="stylesheet" type="text/css" media="all" href="css/5grid/core.css" th:href="@{css/5grid/core}" />
    <link rel="stylesheet" type="text/css" href="css/5grid/core-desktop.css" />
    <link rel="stylesheet" type="text/css" href="css/5grid/core-1200px.css" />
    <link rel="stylesheet" type="text/css" href="css/5grid/core-noscript.css" />
    <link rel="stylesheet" type="text/css" href="css/style.css" />
    <link rel="stylesheet" type="text/css" href="css/style-desktop.css" />

    <script src="css/5grid/jquery.js" type="text/javascript"></script>
    <script src="css/5grid/init.js?use=mobile,desktop,1000px&amp;mobileUI=1&amp;mobileUI.theme=none" type="text/javascript"></script>
    <!--[if IE 9]><link rel="stylesheet" href="css/style-ie9.css" /><![endif]-->
</head>

스프링 프로젝트를 실행하면 내용만 표시되고 CSS는 적용되지 않습니다.그러면 브라우저가 .css,.js 파일의 콘솔 404 Not Found 오류에 다음 오류를 표시합니다.

이 문제를 해결하는 데 도움을 주는 사람이 있다.잘 부탁드립니다.

css를 넣으셔야 합니다./resources/static/css이 변경으로 인해 문제가 해결되었습니다.현재 디렉토리 구조는 다음과 같습니다.

src
  main
    java
      controller
        WebAppMain.java
    resources
      views
        index.html
      static
        css
          index.css
          bootstrap.min.css

템플릿 리졸바는 다음과 같습니다.

public class WebAppMain {

  public static void main(String[] args) {
    SpringApplication app = new SpringApplication(WebAppMain.class);
    System.out.print("Starting app with System Args: [" );
    for (String s : args) {
      System.out.print(s + " ");
    }
    System.out.println("]");
    app.run(args);
  }


  @Bean
  public ViewResolver viewResolver() {
    ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
    templateResolver.setTemplateMode("XHTML");
    templateResolver.setPrefix("views/");
    templateResolver.setSuffix(".html");

    SpringTemplateEngine engine = new SpringTemplateEngine();
    engine.setTemplateResolver(templateResolver);

    ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
    viewResolver.setTemplateEngine(engine);
    return viewResolver;
  }
}

그리고 만약을 위해 여기 제 인덱스가 있습니다.html:

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring3-3.dtd">
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Subscribe</title>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

        <!-- Bootstrap -->
    <link type="text/css" href="css/bootstrap.min.css" rel="stylesheet" />
    <link type="text/css" href="css/index.css" rel="stylesheet" />
</head>
<body>
<h1> Hello</h1>
<p> Hello World!</p>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
</body>
</html>

css 파일을 webapp 리소스 폴더에 넣습니다.

src/main/webapp/resources/css/ 

리소스 핸들러 구성

public class WebConfig extends WebMvcConfigurerAdapter {

        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
                registry.addResourceHandler("/resources/**")
                        .addResourceLocations("/resources/");
        }

프로젝트 예시:

출처:

여러 번 시도해 본 결과, 다음과 같은 효과가 있었습니다.

  1. css 위치:/resources/static/css/stylesheet.css
  2. 링크 경로(html):th:href="@{/css/stylesheet.css}"
  3. Web Security Config:
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/css/**");
    }
    

Spring Boot에서는 뷰에 대한 기본 위치를 검색하려고 합니다.다음 링크를 참조하십시오.

http://docs.spring.io/spring-boot/docs/1.1.4.RELEASE/reference/htmlsingle/ #common-application-properties

실행 가능한 jar를 빌드하는 경우 리소스는 빌드 시 jar에 복사되도록 src/main/webapp이 아닌 src/main/resources에 배치해야 합니다.

index.html은 src/main/resources/templates 아래에 있어야 하지만 정적 리소스는 그렇지 않습니다.기본적으로는 Spring Boot에서 Tymeleaf 뷰를 검색합니다.실제로 Tymeleaf에 대해 뷰 리졸버를 정의할 필요가 없습니다.스프링 부트에서는, 이 설정을 실시합니다.spring-boot-starter-thymeleaf프로젝트에 대한 의존도를 높일 수 있습니다.

# THYMELEAF (ThymeleafAutoConfiguration)
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html # ;charset=<encoding> is added
spring.thymeleaf.cache=true # set to false for hot refresh

다른 사용자가 언급했듯이 css를 src/main/disc/static/css 또는 src/main/disc/public/css에 넣은 후 href="css/5grid"에서 참조합니다.HTML 의 「」가 기능합니다.

저는 같은 문제에 직면해 있었고, 다음과 같은 방법으로 해결했습니다.

  1. 내보낼 폴더를 웹에서 사용할 수 있는지 확인합니다.

    public class WebMvcConfig extends WebMvcConfigurerAdapter {
    
        private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
                "classpath:/META-INF/resources/", "classpath:/resources/",
                "classpath:/static/", "classpath:/public/"
        };
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/**")
                    .addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
        }
    }
    

    또한 css 또는 styles 폴더를 src/main/resources/(static|public|resources|)에 넣어야 합니다.META-INF/Resources) 폴더

  2. 보안 정책에 의해 차단되지 않도록 합니다.

    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        public void configure(WebSecurity web) throws Exception {
            //Web resources
            web.ignoring().antMatchers("/css/**");
            web.ignoring().antMatchers("/scripts/**");
            web.ignoring().antMatchers("/images/**");
        }
    }
    

그만하면 충분할 거야. 

그러나 Spring Boot의 경우 Spring Boot이 정적 콘텐츠에 어떻게 대처하는지 언급할 필요가 있습니다.Spring Boot의 웹 자동 구성이 Spring MVC용으로 bean을 자동으로 구성하는 경우 이러한 bean에는 /**를 여러 리소스 위치에 매핑하는 리소스 핸들러가 포함됩니다.이러한 리소스 위치에는 (클래스 경로의 루트를 기준으로) 다음이 포함됩니다.

  1. /META-INF/리소스/
  2. /timeout/
  3. /static/
  4. /public/

기존의 Maven/Gradle 빌드 애플리케이션에서는 일반적으로 정적 콘텐츠를 src/main/webapp에 저장하여 빌드가 생성하는 WAR 파일의 루트에 배치합니다.Spring Boot에서 WAR 파일을 작성하는 경우에도 마찬가지입니다.그러나 리소스 핸들러에 매핑된 4개의 위치 중 하나에 정적 컨텐츠를 배치할 수도 있습니다.

저도 스프링 부츠를 처음 신는데 같은 문제가 있어요.브라우저에 올바른 경로를 수동으로 입력했고 404 by Tomcat을 확인했습니다.다음으로 Spring-Boot Resource Locations에서 css 파일을 추가하지 않아 404가 발생하는 솔루션을 찾았습니다.

이제 css 파일에 코드로 액세스할 수 있게 되었습니다.

css 폴더를 src/main/resources/static/css로 이동한 후 내용을 읽을 수 있어야 합니다(로컬 설정으로).

 <link href="<%=request.getContextPath()%>/resources/css/bootstrap.min.css" rel="stylesheet" media="screen">
    <link href="<%=request.getContextPath()%>/resources/css/common.css" rel="stylesheet" media="screen">
[this is the image for my project structure. i added the webapp directory to support .jsp files.this method request.getContextPath() worked for me. Hope i help someone with this... it gets the path so long as it exists. 
Nb. You should have a resolver bean in your webconfig
`enter code here`@Bean
public InternalResourceViewResolver viewResolver() {
    InternalResourceViewResolver resolver = new   `enter code here`InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/jsp/");
    resolver.setSuffix(".jsp");
    return resolver;
}` 
for the added directory][1]

언급URL : https://stackoverflow.com/questions/21203402/css-not-loading-in-spring-boot

반응형