I'm seeking guidance on how to properly incorporate static files such as CSS and images in my Spring MVC application using Thymeleaf. Despite researching extensively on this topic, I have not found a solution that works for me. Based on the recommendations from various sources, I placed my CSS and image files in the resources/static/css
and resources/static/images
directories.
https://i.sstatic.net/ehQvE.png
All my HTML files, which require these CSS and image files, are located under templates
within the webapp/WEB-INF/templates
directory.
In my LoginApplicationConfig
file, I added the following two methods at the bottom to enable the use of styles and images in my HTML files:
@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;
}
// Other methods here...
@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);
}
// Other methods here...
}
To include the style file in my index.html file using Thymeleaf, I added the following line:
<link rel="stylesheet" th:href="@{css/stylesmd.css}" type="text/css">
However, I continue to encounter an error stating that the stylesmd.css file failed to load.
My queries are:
- Have I placed my styles and image files correctly? Specifically, where should I place them within my project structure?
- Are the additional methods in
LoginApplicationConfig
necessary? Furthermore, I am unsure about what to include inaddResourceHandler(...)
versusaddResourceLocations(...)
. - Is my reference to the stylesheet (using Thymeleaf) accurate?
Despite the abundance of information available on this issue, none of it has been effective in solving my problem. Hence, I am reaching out for assistance.