有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (6) 个答案

  1. # 1 楼答案

    org.springframework.web.servlet.support.WebContentGenerator是所有Spring控制器的基类,它有许多处理缓存头的方法:

    /* Set whether to use the HTTP 1.1 cache-control header. Default is "true".
     * <p>Note: Cache headers will only get applied if caching is enabled
     * (or explicitly prevented) for the current request. */
    public final void setUseCacheControlHeader();
    
    /* Return whether the HTTP 1.1 cache-control header is used. */
    public final boolean isUseCacheControlHeader();
    
    /* Set whether to use the HTTP 1.1 cache-control header value "no-store"
     * when preventing caching. Default is "true". */
    public final void setUseCacheControlNoStore(boolean useCacheControlNoStore);
    
    /* Cache content for the given number of seconds. Default is -1,
     * indicating no generation of cache-related headers.
     * Only if this is set to 0 (no cache) or a positive value (cache for
     * this many seconds) will this class generate cache headers.
     * The headers can be overwritten by subclasses, before content is generated. */
    public final void setCacheSeconds(int seconds);
    

    它们可以在生成内容之前在控制器内调用,也可以在Spring上下文中指定为bean属性

  2. # 3 楼答案

    您可以为此定义一个地址:@CacheControl(isPublic = true, maxAge = 300, sMaxAge = 300),然后使用Spring MVC拦截器将此地址呈现到HTTP头。或者做动态的:

    int age = calculateLeftTiming();
    String cacheControlValue = CacheControlHeader.newBuilder()
          .setCacheType(CacheType.PUBLIC)
          .setMaxAge(age)
          .setsMaxAge(age).build().stringValue();
    if (StringUtils.isNotBlank(cacheControlValue)) {
        response.addHeader("Cache-Control", cacheControlValue);
    }
    

    可在此处找到含义:优雅的Builder模式

    顺便说一句:我刚刚发现Spring MVC内置了对缓存控制的支持: Google WebContent Interceptor或CacheControlHandlerInterceptor或CacheControl,您将找到它

  3. # 4 楼答案

    答案很简单:

    ^{pr1}$ 上面的代码正好显示了您想要实现的目标。你必须做两件事。添加“final HttpServletResponse”作为参数。然后将标头缓存控制设置为无缓存。

  4. # 5 楼答案

    我只是遇到了同样的问题,并且找到了框架已经提供的一个很好的解决方案。org.springframework.web.servlet.mvc.WebContentInterceptor类允许您定义默认缓存行为,以及特定于路径的重写(与其他地方使用的路径匹配器行为相同)。我的步骤是:

    1. 确保我的org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter实例未设置“cacheSeconds”属性
    2. 添加WebContentInterceptor的实例:

      <mvc:interceptors>
      ...
      <bean class="org.springframework.web.servlet.mvc.WebContentInterceptor" p:cacheSeconds="0" p:alwaysUseFullPath="true" >
          <property name="cacheMappings">
              <props>
                  <!-- cache for one month -->
                  <prop key="/cache/me/**">2592000</prop>
                  <!-- don't set cache headers -->
                  <prop key="/cache/agnostic/**">-1</prop>
              </props>
          </property>
      </bean>
      ...
      </mvc:interceptors>
      

    在这些更改之后,/foo下的响应包含阻止缓存的标题,/cache/me下的响应包含鼓励缓存的标题,/cache/agnostic下的响应不包含与缓存相关的标题


    如果使用纯Java配置:

    @EnableWebMvc
    @Configuration
    public class WebMvcConfig extends WebMvcConfigurerAdapter {
      /* Time, in seconds, to have the browser cache static resources (one week). */
      private static final int BROWSER_CACHE_CONTROL = 604800;
    
      @Override
      public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
         .addResourceHandler("/images/**")
         .addResourceLocations("/images/")
         .setCachePeriod(BROWSER_CACHE_CONTROL);
      }
    }
    

    另见:http://docs.spring.io/spring-security/site/docs/current/reference/html/headers.html

  5. # 6 楼答案

    Spring 4.2开始,您可以执行以下操作:

    import org.springframework.http.CacheControl;
    import org.springframework.http.MediaType;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.concurrent.TimeUnit;
    
    @RestController
    public class CachingController {
        @RequestMapping(method = RequestMethod.GET, path = "/cachedapi")
        public ResponseEntity<MyDto> getPermissions() {
    
            MyDto body = new MyDto();
    
            return ResponseEntity.ok()
                .cacheControl(CacheControl.maxAge(20, TimeUnit.SECONDS))
                .body(body);
        }
    }
    

    CacheControl对象是一个具有许多配置选项的构建器,请参见JavaDoc