css 文件在 Spring 中无法识别

css file is not recognized in Spring

我正在开发一个使用 Spring、Spring MVC、Thymeleaf 和 运行 的网站,遇到问题:css 文件的样式未应用于我的页面。 项目结构如下:

java
   com
      tournament
         config
            MySpringMVCDispatcherServletInitialize.java
            SpConfig.java
         controllers
            HomePageController.java
webapp
   WEB-INF
      views
         css
            style.css
         home_page.html

style.css:

p{
   font-size: 200%;
   font-family: Verdana, Arial, Helvetica, sans-serif;
   color: #336;
}
body{
   background-color: red;
}

home_page.html:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
                xmlns:th="http://thymeleaf.org">
<head>
   <meta charset="UTF-8">
   <title>Title</title>
   <link rel="stylesheet" type="text/css" th:href="@{/css/style.css}" media="all">
</head>
<body>
   <p>Hello</p>
</body>
</html>

在 SpConfig 中有这样的配置:

@Configuration
@ComponentScan("com.tournament")
@EnableWebMvc
public class SpConfig implements WebMvcConfigurer {

    private final ApplicationContext applicationContext;

    @Autowired
    public SpringConfig(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Bean
    public SpringResourceTemplateResolver templateResolver() {
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        templateResolver.setApplicationContext(applicationContext);
        templateResolver.setPrefix("/WEB-INF/views/");
        templateResolver.setSuffix(".html");
        return templateResolver;
    }

    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver());
        templateEngine.setEnableSpringELCompiler(true);
        return templateEngine;
    }

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine());
        registry.viewResolver(resolver);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry {
        registry.addResourceHandler("/css/**")
                .addResourceLocations("/WEB-INF/css/");
}

在 home_page.html 中将光标放在 th:href="@{/css/style.css}" 上,css 文件的路径似乎是正确的,但是在页面 home_page.html 上启动服务器时没有包含任何样式在 style.css。那么我该如何应用这种风格呢?

您的目录结构显示 css 在 WEB-INF/views/css 中,但您在 addResourceLocations 中配置 /WEB-INF/css/。根据 https://www.baeldung.com/spring-mvc-static-resources,如果您不在该字符串中使用 classpath: 前缀,则该路径是相对于 webapp/resources.

所以或者您需要移动您的 CSS,或者您需要更新 .addResourceLocations("/WEB-INF/css/") 声明。