2016-08-18 77 views
0

我的問題是如何添加靜態文件,如CSS和圖像文件,以便我可以使用它們。我正在使用Spring MVC和Thymeleaf。我看了這個主題的各種帖子,但他們沒有幫助我,所以我問。根據這些帖子,我把我的CSS和圖像文件在resources/static/cssresources/static/images directory如何添加靜態文件使用Spring MVC和Thymeleaf

demo

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加載失敗的錯誤。

我的問題:

  1. 是我的風格和圖像文件正確的位置。也就是說,我應該專門將它們放入哪些文件夾中。我嘗試了像webappWEB-INF目錄下的各種位置,但這種方式無效。
  2. 是否需要LoginApplicationConfig中的底部兩種方法?另外,我對addResourceHandler(...)方法中包含的內容以及addResourceLocations(...)方法中的內容有些困惑。
  3. 我參考樣式表(使用thymeleaf)是否正確?

我知道很多內容已經存在於這個問題上,但這對我沒有用,所以這就是爲什麼我問。

回答

1

這就是我的工作方式。 只有一條線就足夠了。

registry.addResourceHandler("/static/**").addResourceLocations("/static/"); 

<head> 
    <link rel="stylesheet" type="text/css" href="/static/css/your.css" th:href="@{/static/css/your.css}"/> 
</head> 

如果它不斷失敗,嘗試移動你「模板」文件夾到資源文件夾的子文件夾。

相關問題