如何使用Spring MVC和Thymeleaf添加静态文件
我的问题是如何添加CSS和图像文件等静态文件,以便我可以使用它们。 我正在使用Spring MVC和Thymeleaf。 我查看了关于这个主题的各种post,但他们没有帮助我,所以我问。 根据这些post,我将我的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文件中,我包含了以下行,因此我可以包含样式文件(使用百日咳):
但我不断收到stylesmd.css无法加载的错误。
我的问题:
- 我的样式和图像文件的位置是否正确。 也就是说,我应该专门将它们放入哪些文件夹中。我尝试了各种位置,例如在
webapp
和WEB-INF
目录下但是没有用。 - 是否需要
LoginApplicationConfig
的底部两个方法? 另外,我对addResourceHandler(...)
方法中包含的内容以及addResourceHandler(...)
方法中的内容感到有些困惑。 - 我对样式表(使用百里香叶)的引用是否正确?
我知道这个问题已经存在很多内容,但这对我没有用,所以这就是我要问的原因。
这就是我的工作方式。 只有一行就足够了。
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
和
如果它一直失败,请尝试将“templates”文件夹作为子文件夹移动到resources文件夹中。