Spring Boot中CSS未加载

29

我刚接触Spring框架和Spring Boot。我正在尝试添加带有CSS、JavaScript和JS的静态HTML文件。文件结构如下:

PROJECT STRUCTURE

我的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。然后浏览器控制台显示以下错误404未找到.css和.js文件

请求帮助解决此问题,谢谢。


我有同样的问题,我认为tomcat没有设置读取css文件夹的权限。但是我也是spring-boot新手,还没有解决方案。 - Huluvu424242
请参考以下链接:https://github.com/spring-guides/tut-spring-security-and-angular-js/tree/master/modular - EpicPandaForce
8个回答

39

你需要将你的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文件放在静态文件夹中的原因可能很有趣,可以考虑添加相关信息。这对我也有效! - Fernando Sanchiz
@FernandoSanchiz 我猜这只是框架的工作方式。我不知道其中的原因是什么。 - Nick Humrich

10

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

src/main/webapp/resources/css/ 

配置资源处理程序

public class WebConfig extends WebMvcConfigurerAdapter {

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

示例项目:

来源:


2
还可以查看Spring Boot文档(在这种情况下可能更相关)。 - Dave Syer
@MariuszS 我已按照上述更改了文件夹结构。现在index.html本身无法加载。浏览器显示以下错误:“HTTP状态500 - 请求处理失败;嵌套异常是org.thymeleaf.exceptions.TemplateInputException:解析模板“index”时出错,模板可能不存在或无法通过任何配置的模板解析器访问”。 - senthil prabhu
5
注:Spring Boot文档不建议将内容放在webapp中,因为默认情况下不会将其添加到可执行的JAR文件中。 - Chris DaMour

6

在多次尝试后,以下方法适用于我:

  1. css location: /resources/static/css/stylesheet.css
  2. link path in html: th:href="@{/css/stylesheet.css}"
  3. WebSecurityConfig:
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/css/**");
    }
    

1
好样例,但是WebSecurityConfig并不是必需的:即使没有它也可以完美运行。 - Vifier Lockla

5

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视图。如果你的项目中有spring-boot-starter-thymeleaf依赖项,你实际上不需要为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中,则可以通过在HTML中引用href =“css/5grid ...”来使用它们。


5

我曾经遇到过同样的问题,以下是我解决问题的方法:

  1. Make sure the folder you are exporting is available to the web

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

    In addition you must put your css or styles folder into your src/main/resources/(static|public|resources|META-INF/resources) folder

  2. Make sure your security policies don't block them

    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/**");
        }
    }
    

这应该足够了。


(此处不需要解释)

2
对于Spring Boot来说,提到Spring Boot如何处理静态内容是值得一提的。当Spring Boot的web自动配置为Spring MVC自动配置bean时,这些bean包括一个资源处理程序,将/**映射到几个资源位置上。这些资源位置包括(相对于类路径的根目录)以下内容:
- /META-INF/resources/ - /resources/ - /static/ - /public/
在传统的Maven/Gradle构建应用程序中,通常会将静态内容放置在src/main/webapp中,以便它可以被放置在构建生成的WAR文件的根目录下。使用Spring Boot构建WAR文件时,这仍然是一个选项。但您也可以选择将静态内容放置在映射到资源处理器的四个位置之一。

1
我也是Spring Boot的新手,遇到了同样的问题。我在浏览器中手动输入正确的路径,看到了Tomcat返回的404错误。之后,我在以下链接找到了解决方案: Spring-Boot ResourceLocations not adding the css file resulting in 404 现在,通过代码可以访问CSS文件。
您必须将CSS文件夹移动到src/main/resources/static/css,然后内容就可以被读取(在我的本地配置中)。

0

 <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`@Beanpublic InternalResourceViewResolver viewResolver() {    InternalResourceViewResolver resolver = new   `enter code here`InternalResourceViewResolver();    resolver.setPrefix("/WEB-INF/jsp/");    resolver.setSuffix(".jsp");    return resolver;}` for the added directory][1]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接