【问题标题】:Cache CSS , JavaScript , Image Spring Boot (+Thymeleaf)缓存 CSS , JavaScript , 图片 Spring Boot (+Thymeleaf)
【发布时间】:2018-10-04 18:31:52
【问题描述】:

我正在使用 Thymeleaf 构建一个 Web Spring Boot。当我刷新或更改页面时,我看到 Thymeleaf 总是加载所有资源,例如 this Thymeleaf。 我如何从内存中缓存资源,类似于 .Net MVC 框架,它可以像this DotNetMVC

【问题讨论】:

    标签: javascript css thymeleaf


    【解决方案1】:

    有两种方法可以做到这一点。

    1. 使用 WebMVCConfig。

    2. 使用 application.properties 文件

    WebMVC 配置。

    像这样创建模板解析器。

    @Bean
    public TemplateResolver templateResolver()
    {
        FileTemplateResolver templateResolver = new FileTemplateResolver();
        templateResolver.setTemplateMode( "HTML5" );
        templateResolver.setCacheable( Boolean.FALSE );
        templateResolver.setOrder( 1 );
        return templateResolver;
    }
    

    应用程序属性

    将以下行添加到 application.properties 文件中

    spring.thymeleaf.cache: false
    

    【讨论】:

    • 感谢@Supun Dharmarathne,但这对他们俩都不起作用。我收到错误:org.thymeleaf.exceptions.TemplateInputException:模板解析期间发生错误(模板:“C:\user\login”)。
    【解决方案2】:

    我看到了其他解决方案

    @Bean
        public WebMvcConfigurer configurer () {
            return new WebMvcConfigurer() {
                @Override
                public void addResourceHandlers(ResourceHandlerRegistry registry) {
                    registry.addResourceHandler("/resources/**")
                            .addResourceLocations("/resources/")                  
                            .setCachePeriod(31556926);
                }
            };
        }
    

    供参考:headers-cache-control 但仍然对我不起作用。我也在使用 Spring Boot Security。

    【讨论】: