[英]How to add static files using Spring MVC and Thymeleaf
我的问题是如何添加静态文件(如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文件中,包括以下行,以便可以包括样式文件(使用百里香):
<link rel="stylesheet" th:href="@{css/stylesmd.css}" type="text/css">
但是我一直收到错误消息,说stylesmd.css无法加载。
我的问题:
webapp
和WEB-INF
目录下的内容,但这没有用。 LoginApplicationConfig
的底部两种方法LoginApplicationConfig
必需? 另外,我是在包括的内容有点糊涂addResourceHandler(...)
的方法,什么addResourceLocations(...)
方法。 我知道这个问题已经有很多内容了,但这对我没有用,所以这就是我要问的原因。
这就是我的工作方式。 仅一行就足够了。
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
和
<head>
<link rel="stylesheet" type="text/css" href="/static/css/your.css" th:href="@{/static/css/your.css}"/>
</head>
如果仍然失败,请尝试将“ templates”文件夹作为子文件夹移动到资源文件夹中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.