CSS未在Spring Boot中加载

CSS not loading in Spring Boot

我是 Spring 框架和 Spring Boot 的新手。我正在尝试使用 CSS、javascript、js 添加静态 html 文件。文件结构是

PROJECT

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<html xmlns:th="http://www.thymeleaf.org">
<head>
    HeavyIndustry by HTML5Templates.com
    <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 src="css/5grid/init.js?use=mobile,desktop,1000px&mobileUI=1&mobileUI.theme=none" type="text/javascript">
    <!--[if IE 9]><link rel="stylesheet" href="css/style-ie9.css" /><![endif]-->
</head>

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

的 404 Not Found 错误

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


你需要把你的css放在/resources/static/css中。此更改为我解决了问题。这是我当前的目录结构。

1
2
3
4
5
6
7
8
9
10
11
12
src
  main
    java
      controller
        WebAppMain.java
    resources
      views
        index.html
      static
        css
          index.css
          bootstrap.min.css

这是我的模板解析器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!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>
    Subscribe
    <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>
 Hello
<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">
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js">
</body>
</html>


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

1
src/main/webapp/resources/css/

配置资源处理程序

1
2
3
4
5
6
7
public class WebConfig extends WebMvcConfigurerAdapter {

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

示例项目:

  • https://github.com/spring-guides/tut-web/tree/master/6/complete
  • 具有静态内容的 Spring Boot 服务模板

来源:

  • 使用 Spring 设计和实现 Web 应用程序
  • 使用 Spring MVC 提供 Web 内容


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

  • 确保您要导出的文件夹可用于网络

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    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 或样式文件夹放入您的 src/main/resources/(static|public|resources|META-INF/resources) 文件夹

  • 确保您的安全策略不会阻止它们

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    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 将尝试在一些默认位置查找您的视图。看看下面的链接。

    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 将为您设置。

    1
    2
    3
    4
    5
    6
    7
    # 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 中应该可以工作。


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

  • CSS 位置:/resources/static/css/stylesheet.css
  • html 中的链接路径:th:href="@{/css/stylesheet.css}"
  • 网络安全配置:

    1
    2
    3
    4
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/css/**");
    }

  • In the case of Spring Boot, however, ita€?s worth mentioning how Spring
    Boot deals with static content. When Spring Boota€?s web
    autoconfiguration is automatically configuring beans for Spring MVC,
    those beans include a resource handler that maps /** to several
    resource locations. Those resource locations include (relative to the
    root of the classpath) the following:

  • /META-INF/资源/
  • /资源/
  • /静止的/
  • /上市/
  • In a conventional Maven/Gradle-built application, youa€?d typically put
    static content at src/main/webapp so that it would be placed at the
    root of the WAR file that the build produces. When building a WAR file
    with Spring Boot, thata€?s still an option. But you also have the option
    of placing static content at one of the four locations mapped to the
    resource handler.


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

    的 css 文件

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

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


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
     <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]