我的问题是如何添加 CSS 和图像文件等静态文件,以便我可以使用它们。我正在使用 Spring MVC 和 Thymeleaf。我查看了有关此主题的各种帖子,但它们对我没有帮助,所以我才来问。根据这些帖子,我将 CSS 和图像文件放在resources/static/css
and resources/static/images directory
.
Under templates
(under webapp/WEB-INF/templates
) 是我所有 HTML 文件的存储位置,那些想要使用 CSS 和图像文件的文件。
我有以下内容LoginApplicationConfig
文件。我包含了两个底部方法,以便我的 HTML 文件可以使用样式和图像文件:
@EnableWebMvc
@Configuration
@ComponentScan({ "com.myapp.spring.*" })
@Import(value = { LoginSecurityConfig.class })
public class LoginApplicationConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware{
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Bean
public ViewResolver viewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
resolver.setCharacterEncoding("UTF-8");
return resolver;
}
@Bean
public TemplateEngine templateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setEnableSpringELCompiler(true);
engine.setTemplateResolver(templateResolver());
return engine;
}
private ITemplateResolver templateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("/WEB-INF/templates/");
resolver.setTemplateMode(TemplateMode.HTML);
return resolver;
}
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/static/css").setCachePeriod(31556926);
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/static/images").setCachePeriod(31556926);
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
然后在我的 index.html 文件中,我包含了以下行,这样我就可以包含样式文件(使用 thymeleaf):
<link rel="stylesheet" th:href="@{css/stylesmd.css}" type="text/css">
但我不断收到 stylesmd.css 无法加载的错误。
我的问题:
- 我的样式和图像文件的放置正确吗?也就是说,我应该专门将它们放入哪些文件夹中。我尝试了各种位置,例如在
webapp
and WEB-INF
目录但这不起作用。
- 下面的两个方法是
LoginApplicationConfig
必需的?此外,我对在其中包含哪些内容感到有点困惑addResourceHandler(...)
方法以及其中的内容addResourceLocations(...)
method.
- 我对样式表(使用百里香)的引用正确吗?
我知道这个问题已经存在很多内容,但这对我不起作用,所以这就是我问的原因。
这就是我让它发挥作用的方法。
只需要一行就够了。
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
And
<head>
<link rel="stylesheet" type="text/css" href="/static/css/your.css" th:href="@{/static/css/your.css}"/>
</head>
如果仍然失败,请尝试将“模板”文件夹作为子文件夹移动到资源文件夹中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)