簡體   English   中英

如何使用Spring MVC和Spring Security為資源處理程序啟用HTTP緩存

[英]How to enable HTTP caching for the resource handler with Spring MVC and Spring Security

我希望為一些靜態資源啟用HTTP緩存,例如圖像,其訪問受到Spring Security的限制。 (這些資源不是安全關鍵,但也不應公開訪問)。 如何避免讓Spring Security添加禁用緩存的HTTP響應頭?

如果我將setCachePeriod()添加到WebMvcConfigurerAdapter.addResourceHandlers()資源處理程序注冊中,如下所示:

registry.addResourceHandler("/static/**")
  .addResourceLocations("classpath:/static/").setCachePeriod(3600);

仍然返回資源以及禁用緩存的以下標頭:

Cache-Control: max-age=3600, must-revalidate
Expires: Mon, 04 Aug 2014 07:45:36 GMT
Pragma: no-cache

我想避免在項目中引入任何XML配置,該項目目前僅使用Java注釋配置。

有沒有比擴展Spring資源處理程序更好的解決方案?

您可以使用webContentInterceptor資源來允許靜態資源緩存。

<mvc:interceptors>
    <mvc:interceptor>
    <mvc:mapping path="/static/*"/>
        <bean id="webContentInterceptor" class="org.springframework.web.servlet.mvc.WebContentInterceptor">
            <property name="cacheSeconds" value="31556926"/>
            <property name="useExpiresHeader" value="true"/>
            <property name="useCacheControlHeader" value="true"/>
            <property name="useCacheControlNoStore" value="true"/>
        </bean>
   </mvc:interceptor>
</mvc:interceptors>

使用注釋來配置緩存攔截器是按照以下方式完成的。 在您的Web配置類中,您可以為WebContentInterceptor類添加一個bean,並將其添加到攔截器列表中。

@Bean
public WebContentInterceptor webContentInterceptor() {
    WebContentInterceptor interceptor = new WebContentInterceptor();
    interceptor.setCacheSeconds(31556926);
    interceptor.setUseExpiresHeader(true);;
    interceptor.setUseCacheControlHeader(true);
    interceptor.setUseCacheControlNoStore(true);
    return interceptor;
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(webContentInterceptor());
}

請參閱此網站 ,了解它是如何完成的。

Spring 4文檔有這個解決方案,“如果你真的想要緩存特定的響應,你的應用程序可以選擇性地調用HttpServletResponse.setHeader(String,String)來覆蓋Spring Security設置的頭”。 這有助於確保正確緩存CSS,JavaScript和圖像等內容。

以下片段可用於springmvc配置,

@EnableWebMvc
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {

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

// ...
}

供參考: http//docs.spring.io/spring-security/site/docs/4.0.0.CI-SNAPSHOT/reference/htmlsingle/#headers-cache-control

您已經設置了緩存。 必須重新驗證意味着一旦緩存過期(3600秒)不再使用它,所以我認為你的響應標題對於你想要的是正確的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM