【问题标题】:CSS not loading in Spring BootCSS未在Spring Boot中加载
【发布时间】:2014-02-07 19:35:58
【问题描述】:

我是 Spring 框架和 Spring Boot 的新手。我正在尝试使用 CSS、javascript、js 添加静态 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>

当我运行 spring 项目时,仅显示内容并且未应用 CSS。然后浏览器在控制台中显示以下错误 .css、.js 文件的 404 Not Found 错误

有人帮我解决这个问题。在此先感谢。

【问题讨论】:

标签: spring spring-mvc spring-boot


【解决方案1】:

您需要将您的 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;
  }
}

以防万一,这是我的 index.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 文件放入静态文件夹的信息可能会很有趣。它也适用于我!
  • @FernandoSanchiz 我认为这就是框架的工作方式。我不知道why 是什么。
【解决方案2】:

css文件放入webapp资源文件夹:

src/main/webapp/resources/css/ 

配置资源处理程序

public class WebConfig extends WebMvcConfigurerAdapter {

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

示例项目:

来源:

【讨论】:

  • 另见Spring Boot docs(在这种特殊情况下可能更相关)。
  • @MariuszS 我已经改变了上面提到的文件夹结构。现在 index.html 本身没有加载。浏览器显示以下错误“HTTP 状态 500 - 请求处理失败;嵌套异常是 org. thymeleaf.exceptions.TemplateInputException:解析模板“索引”时出错,模板可能不存在或可能无法被任何已配置的模板解析器访问”
  • 仅供参考:spring boot 文档不鼓励将内容放入 webapp,因为默认情况下它不会添加到可执行 jar 中
【解决方案3】:

Spring Boot 将尝试在一些默认位置查找您的视图。看看下面的链接。

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

如果您正在构建可执行 jar,则您的资源应放在 src/main/resources 下,而不是 src/main/webapp 下,以便在构建时将它们复制到您的 jar 中。

你的 index.html 应该像你已经拥有的那样放在 src/main/resources/templates 下,但你的静态资源不应该。 Spring Boot 默认会在那里寻找你的 Thymeleaf 视图。而且您实际上不需要为 Thymeleaf 定义自己的视图解析器,如果您的项目中有 spring-boot-starter-thymeleaf 依赖项,Spring Boot 将为您设置。

# 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/resources/static/css 或 src/main/resources/public/css 中,然后在您的 href="css/5grid..." 中引用它们HTML 应该可以工作。

【讨论】:

    【解决方案4】:

    我遇到了同样的问题并通过以下方式解决了它:

    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);
          }
      }
      

      此外,您必须将 cssstyles 文件夹放入您的 src/main/resources/static|公共|资源|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/**");
          }
      }
      

    应该够了

    【讨论】:

      【解决方案5】:

      经过多次尝试,这对我有用:

      1. css 位置:/resources/static/css/stylesheet.css
      2. html 中的链接路径:th:href="@{/css/stylesheet.css}"
      3. 网络安全配置:
        @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers("/css/**");
        }
        

      【讨论】:

      • 很好的示例,但 WebSecurityConfig 不是强制性的:没有它也可以完美运行。
      【解决方案6】:

      然而,在 Spring Boot 的情况下,值得一提的是 Spring 如何 Boot 处理静态内容。当 Spring Boot 的 web 自动配置为 Spring MVC 自动配置 bean, 这些 bean 包括一个资源处理程序,将 /** 映射到几个 资源位置。这些资源位置包括(相对于 类路径的根目录)如下:

      1. /META-INF/resources/
      2. /资源/
      3. /静态/
      4. /公共/

      在传统的 Maven/Gradle 构建的应用程序中,您通常会将 src/main/webapp 中的静态内容,以便将其放置在 构建生成的 WAR 文件的根目录。构建 WAR 文件时 使用 Spring Boot,这仍然是一种选择。但你也有选择 将静态内容放置在映射到的四个位置之一 资源处理程序。

      【讨论】:

        【解决方案7】:

        我也是 Spring Boot 新手,遇到了同样的问题。 我已将正确的路径手动放入浏览器,并通过 tomcat 看到了 404。 然后我在以下位置找到了解决方案: Spring-Boot ResourceLocations not adding the css file resulting in 404

        现在可以通过代码访问 css 文件了。

        您必须将 css 文件夹移动到 src/main/resources/static/css 然后内容才可读(在我的本地配置中)。

        【讨论】:

          【解决方案8】:

           <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]

          【讨论】:

            猜你喜欢
            • 2019-05-16
            • 2019-06-23
            • 1970-01-01
            • 2018-11-22
            • 2018-10-02
            • 2019-06-07
            • 2016-03-04
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多