我正在使用 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
樣式.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. 那么我該如何應用這種風格呢?
uj5u.com熱心網友回復:
您的目錄結構顯示 css 在 中WEB-INF/views/css,但您/WEB-INF/css/在addResourceLocations. 根據https://www.baeldung.com/spring-mvc-static-resources,如果您不在classpath:該字串中使用前綴,則路徑是相對于webapp/resources.
所以或者你需要移動你的 CSS,或者你需要更新.addResourceLocations("/WEB-INF/css/")陳述句。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/360871.html
