【问题标题】:Spring-Boot ResourceLocations not finding css file in resources/static/cssSpring-Boot ResourceLocations 在资源/静态/css 中找不到 css 文件
【发布时间】:2015-10-02 05:41:40
【问题描述】:

在我的 Spring Boot 项目中,当我进行 maven 构建时,没有找到我的 css 样式表。我已经从 Spring Boot 官方文档和其他 stackoverflow 帖子中获得了建议,并将我的 css 文件放在了 resources/static/css 目录中。

|_src
   |_main
   |_java
   |_resources
      |_templates
      |_static
         |_css
            |_master.css

在thymeleaf布局中声明css样式表(templates目录下的html文件):

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ipp="" xmlns:th="http://www.thymeleaf.org">
<head>
    <link rel="stylesheet" href="../static/css/master.css" th:href="@{/css/master.css}" media="screen"/>
</head>

我的 pom.xml 包含 spring-boot-starter-web 和 spring-boot-starter-thymeleaf,因此预计 Spring-Boot ResourceLocations 应该将静态内容映射到 src/main/resources/static。

我也尝试过:

th:href="@{css/master.css}"

th:href="@{static/css/master.css}"

th:href="@{../static/css/master.css}"

并完全删除 th:href=...

关于是什么阻止样式表被定位的任何想法?

【问题讨论】:

  • 这是正确的版本 th:href="@{css/master.css}" 显示呈现的 HTML 输出。也尝试使用localhost:8080/css/master.css 直接访问css
  • 模板和静态文件应该存储在 /WEB-INF 而不是 /resources 下。我认为这个资源可能会有所帮助:thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html
  • 我曾尝试将模板和静态数据存储在 Spring Boot 映射到的不同选项下,包括 /WEB-INF。 5天后,它神奇地开始在当前目录结构下工作,但我不知道最初的问题是什么?这不可能是对代码的修改,因为该问题跨越多个单独的项目,然后开始为所有项目工作。
  • 此代码添加 spring-config.xml 时,我解决了我的问题

标签: css spring maven spring-boot thymeleaf


【解决方案1】:

我看到你有一个正确的项目树。这意味着所有 cssjsimage 文件都必须在 static 文件夹中,该文件夹也需要在以下文件夹 src/main/resources/

文件夹 static/ 提供。类似的东西,src/main/resources/static/master.css 将从 /master.css

提供

More explanations

package com.lab;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 *
 * @author mdbah
 */

@EnableWebMvc 
@Configuration
public class Webconfig extends WebMvcConfigurerAdapter{
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry){
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");

    }
}

我还使用这个类在我的项目中包含 webjars 引导程序,这阻止了从静态文件夹加载我的 css 和 js 文件。 因此,我简单地删除了 @EnableWebMvc 注释,然后重新编译了项目。现在,瞧

如果你在这种情况下,这种方法可以调节你的关注

PS: 对不起,我的英语不好,希望你能明白一些事情

【讨论】:

    猜你喜欢
    • 2019-05-20
    • 2012-05-16
    • 2014-07-07
    • 1970-01-01
    • 2018-03-01
    • 2016-10-01
    • 2017-05-27
    • 1970-01-01
    • 2019-07-14
    相关资源
    最近更新 更多