带有 Thymeleaf 的 SpringBoot - 找不到 css [英] SpringBoot with Thymeleaf - css not found

查看:109
本文介绍了带有 Thymeleaf 的 SpringBoot - 找不到 css的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先要说的是,我一直在寻找解决方案有一段时间了,现在我很绝望.

First to say is that I've been searching for a solution for a while now and I'm quite desperate now.

当 Spring Boot 运行时,我无法从 html 页面访问 css 文件.

I cannot get the css file to be accessible from html page when run by Spring Boot.

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

应用程序.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/*");
    }
}

文件夹结构:

我尝试将 css 文件夹放入 static 文件夹和/或删除 addResourcesHandlers,通过相对路径和其他一些东西引用 css.似乎没有什么可以解决这个问题.如果您尝试解决此问题但没有找到解决方案,也请告诉我,以便我知道我不会被忽略.

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

推荐答案

问题出在 Application.java 文件中的 @EnableWebMvc 注释.一旦我删除了那个,css 就开始在 localhost:8080/css/style.css 上可用,但没有应用.到目前为止,我还没有找到 @EnableWebMvc 导致问题的原因.

The problem was the @EnableWebMvc annotation in the Application.java file. As soon as I removed that one, the css started to be available at localhost:8080/css/style.css but was not applied. So far I haven't found the reason why the @EnableWebMvc was causing the problem.

然后我删除了一个映射到 /** 的控制器,我已经实现了该控制器以显示自定义错误页面.

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

在删除这个之后,我的 css 就可以工作了.=)

After removing also this one, I've got my css working. =)

这篇关于带有 Thymeleaf 的 SpringBoot - 找不到 css的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆