简体   繁体   English

带有 Thymeleaf 的 SpringBoot - css 未找到

[英]SpringBoot with Thymeleaf - css not found

First to say is that I've been searching for a solution for a while now and I'm quite desperate now.首先要说的是,我一直在寻找解决方案有一段时间了,现在我非常绝望。

I cannot get the css file to be accessible from html page when run by Spring Boot.当 Spring Boot 运行时,我无法从 html 页面访问 css 文件。

html.file html.文件

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
    <head lang="en">
        <title th:text='#{Title}'>AntiIntruder</title>
        <meta charset="UTF-8" />
        <link rel="stylesheet" type="text/css" media="all" href="../assets/css/style.css" th:href="@{/css/style.css}" />
    </head>
    <body>
...

Application.java应用.java

@SpringBootApplication // adds @Configuration, @EnableAutoConfiguration, @ComponentScan
@EnableWebMvc
public class Application extends WebMvcConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

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

folder structure:文件夹结构:

文件夹结构

I've tried putting the css folder into a static folder and/or removing the addResourcesHandlers, referencing to the css by relative path and some other things.我试过将css文件夹放入static文件夹和/或删除 addResourcesHandlers,通过相对路径和其他一些东西引用 css。 Nothing seems to resolve this.似乎没有什么可以解决这个问题。 Please, let me know also if you tried to solve this but did not find a solution, so that I know, that I'm not ignored.如果您尝试解决此问题但没有找到解决方案,请也让我知道,以便我知道,我没有被忽略。

1. Using Custom Resource Path 1.使用自定义资源路径

In your Web Config 在您的Web配置中

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
  if (!registry.hasMappingForPattern("/assets/**")) {
     registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/assets/");
  }
}

Put your style.css file inside this folder style.css文件放在此文件夹中

src/main/resources/assets/css/

After that in your views 在你的意见之后

<link rel="stylesheet" type="text/css" th:href="@{/assets/css/style.css}" />

.

2. Using predefined paths in spring boot 2.在弹簧引导中使用预定义路径

Remove addResourceHandlers from your web config 从Web配置中删除addResourceHandlers

Put the style.css inside any of the following folders style.css放在以下任何文件夹中

  • src/main/resources/META-INF/resources/assets/css
  • src/main/resources/resources/assets/css/
  • src/main/resources/static/assets/css/
  • src/main/resources/public/assets/css/

And in the view 并在视图中

<link rel="stylesheet" type="text/css" th:href="@{/assets/css/style.css}" />

.

NOTE: You can remove the assets folder here. 注意:您可以在此处删除assets文件夹。 If you want to do it, remove it from the predefined resource folder and also from the view th:href . 如果要这样做,请将其从预定义的资源文件夹中删除,也可以从view th:href删除。 But i kept it as it is because, you explicitly mentioned the assets/ path in your question. 但我保持原样,因为你明确提到了问题中的assets/路径。 So I belive it's your requirement to have assets/ in your resource URL. 所以我相信你需要在资源URL中拥有assets/

The problem was the @EnableWebMvc annotation in the Application.java file. 问题是Application.java文件中的@EnableWebMvc注释。 As soon as I removed that one, the css started to be available at localhost:8080/css/style.css but was not applied. 一旦我删除了那个,css就开始在localhost:8080/css/style.css上可用,但是没有应用。 So far I haven't found the reason why the @EnableWebMvc was causing the problem. 到目前为止,我还没有找到@EnableWebMvc导致问题的原因。

Then I removed a controller mapped to /** that I had implemented in order to display custom error page. 然后我删除了一个映射到我已实现的/**的控制器,以显示自定义错误页面。

@RequestMapping("/**")
public String notFound() {
    return "errors/404";
}

After removing also this one, I've got my css working. 除去这个之后,我的css正在工作。 =) =)

If you put your css in the static folder, you dont need the addResourceHandlers method. 如果将css放在静态文件夹中,则不需要addResourceHandlers方法。

.../static/css/app.css

Or if you really want to put them in the assets folder: 或者,如果您真的想将它们放在assets文件夹中:

.addResourceLocations("classpath:/assets/") <-- without the * at the end
.../assets/css/app/css

in both cases the css should be available through 在这两种情况下,css都应该可以通过

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

我的建议是将(再次) css文件夹放在static文件夹下,删除addResourcesHandlers并使用绝对路径到达css(例如/css/style.css )。

将您的css文件夹放在resources / static文件夹中

For me I had to remove the static reference to the stylesheet for it to work in thymeleaf. 对我来说,我不得不删除样式表的静态引用,以便在百里香中工作。 So 所以

<link rel="stylesheet" type="text/css" media="all" href="../assets/css/style.css" th:href="@{/css/style.css}">

Became 成为

<link rel="stylesheet" th:href="@{/css/bootstrap.css}"> 

I spent hours trying all sorts of configurations and file path renaming. 我花了好几个小时尝试各种配置和文件路径重命名。 Don't know why but this is the only thing that got my css and js to load in Spring Boot 5. 不知道为什么,但这是唯一让我的css和js加载到Spring Boot 5中的东西。

In my case the problem was in file read permissions.就我而言,问题出在文件读取权限上。 I copied the file 'style.css' from another project, and browser could not read it.我从另一个项目复制了文件“style.css”,浏览器无法读取它。 After re-creating 'style.css', everything worked fine.重新创建“style.css”后,一切正常。

first implements on one of your configuration class with WebMvcConfigurer like this首先像这样使用 WebMvcConfigurer 在您的配置 class 之一上实现

@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
//and overide this configuration method like this    
@Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/webjars/**", "/resources/**");
    }
}

so now you can overide your HttpSecurity configuration like this所以现在你可以像这样覆盖你的 HttpSecurity 配置

@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter{
 
   @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                        .antMatchers("/", "/index").anonymous()
                        .antMatchers("/**/*.*").permitAll()
                .anyRequest().authenticated();
    }
}

this ("/**/*.*") regex text will allow files with anny extension

and if your are using an webjars libraries like bootstrap add this config to your WebSecurityConfiguration如果您使用的是像 bootstrap 这样的 webjars 库,请将此配置添加到您的 WebSecurityConfiguration

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}

If this topic still relevant in 2022. I have had a similar problem and i solved it like this:如果这个主题在 2022 年仍然相关。我遇到过类似的问题,我是这样解决的:

This link in /templates/file.html这个链接在/templates/file.html

<link rel="stylesheet" type="text/css" media="all" ref="../static/css/styles.css">

and i have added application.properties我添加了 application.properties

spring.mvc.static-path-pattern=/static/**

my css path is我的 css 路径是

 src/main/resources/static/css/

helpful link有用的链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM