【发布时间】:2016-12-25 18:32:00
【问题描述】:
我的问题是如何添加静态文件,如 CSS 和图像文件,以便我可以使用它们。我正在使用 Spring MVC 和 Thymeleaf。我查看了有关此主题的各种帖子,但它们对我没有帮助,所以我在问。根据这些帖子,我将我的 CSS 和图像文件放在 resources/static/css 和 resources/static/images directory 中。
templates 下(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和WEB-INF目录下的各种位置,但没有奏效。 -
LoginApplicationConfig下面的两个方法是必需的吗?此外,我对在addResourceHandler(...)方法中包含什么以及在addResourceLocations(...)方法中包含什么感到有些困惑。 - 我对样式表的引用(使用 thymeleaf)是否正确?
我知道这个问题已经有很多内容了,但这对我没有用,所以这就是我问的原因。
【问题讨论】:
标签: java css spring spring-mvc thymeleaf