CSS 未在 Spring Boot 中加载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21203402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 06:27:56  来源:igfitidea点击:

CSS not loading in Spring Boot

springspring-mvcspring-boot

提问by senthil prabhu

I am new to spring frame work and spring boot.I am trying to add the static html file with CSS,javascript,js. the file structure is

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

PROJECT STRUCTURE

项目结构

and my html file head looks like this

我的 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>

when i run the spring project only the content is shown and the CSS is not applied.then the browser show the following error in the console 404 Not Found error for the .css,.js files

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

some body help me to sort out this issue.Thanks in Advance.

一些机构帮我解决了这个问题。提前致谢。

回答by Nick Humrich

You need to put your css in /resources/static/css. This change fixed the problem for me. Here is my current directory structure.

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

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

Here is my template resolver:

这是我的模板解析器:

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

And just in case, here is my index.html:

以防万一,这是我的 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>

回答by MariuszS

Put cssfiles into webappresources folder:

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

src/main/webapp/resources/css/ 

Configure resource handler

配置资源处理程序

public class WebConfig extends WebMvcConfigurerAdapter {

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

Example projects:

示例项目:

Source:

来源:

回答by Patrick Grimard

Spring Boot will attempt to look in some default locations for your views. Have a look at the following link.

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

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

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

If you're building an executable jar, your resources should be placed under src/main/resources, not src/main/webapp so that they're copied into your jar at build time.

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

Your index.html should go under src/main/resources/templates like you've got it, but your static resources shouldn't. Spring Boot will look for your Thymeleaf views there by default. And you don't actually need to define your own view resolver for Thymeleaf, Spring Boot will set this up for you if you have the spring-boot-starter-thymeleafdependency in your project.

你的 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

As mentioned by others, if you put your css in src/main/resources/static/css or src/main/resources/public/css, then referencing them from href="css/5grid..." in your HTML should work.

正如其他人所提到的,如果您将 css 放在 src/main/resources/static/css 或 src/main/resources/public/css 中,那么从 HTML 中的 href="css/5grid..." 引用它们应该可以工作.

回答by EliuX

I was facing the same issues and solved it the following way:

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

  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 cssor stylesfolder 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/**");
        }
    }
    
  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样式文件夹放入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/**");
        }
    }
    

That should be enough

那应该够了

回答by rajeev pani..

In the case of Spring Boot, however, it's worth mentioning how Spring Boot deals with static content. When Spring Boot'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:

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

  1. /META-INF/resources/
  2. /resources/
  3. /static/
  4. /public/
  1. /元信息/资源/
  2. /资源/
  3. /静止的/
  4. /民众/

In a conventional Maven/Gradle-built application, you'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, that'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.

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

回答by pawszo

This is what worked for me after many attempts:

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

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

回答by FunThomas424242

I'm new to spring boot too and I have the same problem. I have put the correct path manually into the browser and have seen the 404 by tomcat. Then I have found a solution at: Spring-Boot ResourceLocations not adding the css file resulting in 404

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

Now the css file is accessible by code.

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

You must move the css folder to src/main/resources/static/css then the content is readable (at my local configuration).

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

I hope it works at your configuration too.

我希望它也适用于您的配置。

回答by Fred Kibuchi

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