복붙노트

[SPRING] Spring MVC에서 캐시 헤더를 어떻게 설정합니까?

SPRING

Spring MVC에서 캐시 헤더를 어떻게 설정합니까?

어노테이션 기반 Spring MVC 컨트롤러에서 특정 경로에 대한 캐시 헤더를 설정하는 가장 좋은 방법은 무엇입니까?

해결법

  1. ==============================

    1.모든 Spring 컨트롤러의 기본 클래스 인 org.springframework.web.servlet.support.WebContentGenerator는 캐시 헤더를 다루는 꽤 많은 메소드를 가지고 있습니다 :

    모든 Spring 컨트롤러의 기본 클래스 인 org.springframework.web.servlet.support.WebContentGenerator는 캐시 헤더를 다루는 꽤 많은 메소드를 가지고 있습니다 :

    /* 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. ==============================

    2.방금 같은 문제가 발생하여 프레임 워크가 이미 제공 한 좋은 솔루션을 발견했습니다. org.springframework.web.servlet.mvc.WebContentInterceptor 클래스를 사용하면 기본 캐싱 동작과 경로 별 재정의 (다른 곳에서 사용되는 것과 동일한 경로 일치 동작)를 정의 할 수 있습니다. 나를위한 단계는 다음과 같습니다.

    방금 같은 문제가 발생하여 프레임 워크가 이미 제공 한 좋은 솔루션을 발견했습니다. org.springframework.web.servlet.mvc.WebContentInterceptor 클래스를 사용하면 기본 캐싱 동작과 경로 별 재정의 (다른 곳에서 사용되는 것과 동일한 경로 일치 동작)를 정의 할 수 있습니다. 나를위한 단계는 다음과 같습니다.

    이러한 변경 이후 / 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

  3. ==============================

    3.대답은 아주 간단합니다.

    대답은 아주 간단합니다.

    @제어 장치 공용 클래스 EmployeeController {     @RequestMapping (value = "/ find / employer / {employerId}", method = RequestMethod.GET)     public List getEmployees (@PathVariable ( "employerId") 긴 employerId, 최종 HttpServletResponse 응답) {         response.setHeader ( "Cache-Control", "no-cache");         return employeeService.findEmployeesForEmployer (employerId);     } }

  4. ==============================

    4.Spring 4.2부터는 다음과 같이 할 수 있습니다 :

    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 참조).

  5. ==============================

    5.당신은 Handler Interceptor를 사용하고 그것으로 제공되는 postHandle 메소드를 사용할 수 있습니다 :

    당신은 Handler Interceptor를 사용하고 그것으로 제공되는 postHandle 메소드를 사용할 수 있습니다 :

    http://static.springsource.org/spring/docs/2.0.x/api/org/springframework/web/servlet/HandlerInterceptor.html

    postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) 
    

    메서드에 다음과 같이 헤더를 추가하면됩니다.

    response.setHeader("Cache-Control", "no-cache");
    
  6. ==============================

    6.@CacheControl (isPublic = true, maxAge = 300, sMaxAge = 300)의 애노테이션을 정의한 다음이 애노 테이션을 Spring MVC 인터셉터가있는 HTTP 헤더로 렌더링 할 수있다. 또는 그것을 동적으로하십시오 :

    @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);
    }
    

    여기에 함축 된 의미 : 우아한 작성기 모드

    BTW : 스프링 MVC에 캐시 컨트롤에 대한 빌드 인 지원이 있다는 것을 알았습니다. Google WebContentInterceptor 또는 CacheControlHandlerInterceptor 또는 CacheControl을 찾을 수 있습니다.

  7. ==============================

    7.나는 이것이 정말로 오래된 것이지만 인터넷 검색을하는 사람들에게 도움이 될 수 있음을 안다.

    나는 이것이 정말로 오래된 것이지만 인터넷 검색을하는 사람들에게 도움이 될 수 있음을 안다.

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
    
        WebContentInterceptor interceptor = new WebContentInterceptor();
    
        Properties mappings = new Properties();
        mappings.put("/", "2592000");
        mappings.put("/admin", "-1");
        interceptor.setCacheMappings(mappings);
    
        registry.addInterceptor(interceptor);
    }
    
  8. ==============================

    8.AnnotationMethodHandlerAdapter를 확장하여 사용자 정의 캐시 제어 주석을 찾고 그에 따라 http 헤더를 설정할 수 있습니다.

    AnnotationMethodHandlerAdapter를 확장하여 사용자 정의 캐시 제어 주석을 찾고 그에 따라 http 헤더를 설정할 수 있습니다.

  9. ==============================

    9.컨트롤러에서 응답 헤더를 직접 설정할 수 있습니다.

    컨트롤러에서 응답 헤더를 직접 설정할 수 있습니다.

    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    
  10. ==============================

    10.WebContentInterceptor가 가장 쉬운 방법이라는 것을 알았습니다.

    WebContentInterceptor가 가장 쉬운 방법이라는 것을 알았습니다.

    @Override
    public void addInterceptors(InterceptorRegistry registry)
    {
        WebContentInterceptor interceptor = new WebContentInterceptor();
        interceptor.addCacheMapping(CacheControl.noCache(), "/users", "admin");
        registry.addInterceptor(interceptor);
    }
    
  11. from https://stackoverflow.com/questions/1362930/how-do-you-set-cache-headers-in-spring-mvc by cc-by-sa and MIT license