2014-06-11 8 views
33

스프링 부트 1.0.2를 사용하여 REST 서버를 구현했습니다. HTTP 캐싱을 사용하지 못하게하는 HTTP 헤더를 설정하지 못하게하는 데 문제가 있습니다.스프링 부트에서 HTTP 응답 캐싱을 사용하는 방법

내 컨트롤러는 다음과 같습니다 :

@Controller 
public class MyRestController { 
    @RequestMapping(value = "/someUrl", method = RequestMethod.GET) 
    public @ResponseBody ResponseEntity<String> myMethod(
      HttpServletResponse httpResponse) throws SQLException { 
     return new ResponseEntity<String>("{}", HttpStatus.OK); 
    } 
} 

모든 HTTP 응답은 다음과 같은 헤더가 포함되어

    : 나는 그 헤더를 제거하거나 변경하려면 다음을 시도했습니다

    Cache-Control: no-cache, no-store, max-age=0, must-revalidate 
    Expires: 0 
    Pragma: no-cache 
    

  1. 컨트롤러에서 setCacheSeconds(-1)으로 전화하십시오.
  2. 컨트롤러의 httpResponse.setHeader("Cache-Control", "max-age=123")으로 전화하십시오.
  3. setCacheSeconds(-1)에 대해 WebContentInterceptor을 반환하는 @Bean을 정의하십시오.
  4. 속성을 spring.resources.cache-period으로 설정하거나 -1을 양수로 설정하면 application.properties이됩니다.

위의 것들 중 아무 것도 영향을 미치지 않았습니다. Spring Boot의 모든 요청이나 개별 요청에 대해 어떻게 헤더를 비활성화하거나 변경합니까?

+1

나는 생각하지 않는다 봄 부트는 않습니다 (어쨌든 시도한 샘플 중 하나에 포함되지 않음). 응답에 이러한 헤더가있는 최소한의 프로젝트를 공유 할 수 있습니까? –

+1

당신이 옳습니다. 범인은 봄 보안으로 밝혀졌습니다. –

답변

38

no-cache HTTP 헤더는 Spring Security에 의해 설정된다. 이에 대해서는 http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#headers에서 논의됩니다.

다음은 HTTP 응답 헤더 Pragma: no-cache을 비활성화하지만, 그 문제가 해결되지 않는 : 나는 (위와 같은 클래스에서) 다음과 같은 공공 정적 자원을 완전히 봄 보안을 해제 결국

import org.springframework.context.annotation.Configuration; 
import org.springframework.security.config.annotation.web.builders.HttpSecurity; 
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity; 

@Configuration 
@EnableWebMvcSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 
    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     // Prevent the HTTP response header of "Pragma: no-cache". 
     http.headers().cacheControl().disable(); 
    } 
} 

을 :

@Override 
public void configure(WebSecurity web) throws Exception { 
    web.ignoring().antMatchers("/static/public/**"); 
} 

이 잘 캐시 제어 헤더를 얻을 수있는 두 개의 자원 핸들러 구성이 필요합니다

,654,512을

도 참조하십시오. Serving static web resources in Spring Boot & Spring Security application.

+2

http://stackoverflow.com/a/36459244/759042에 설명 된대로 특정 컨트롤러 동작에 대해 다른 Cache-Control 헤더를 사용하려는 경우 Spring Security를 ​​완전히 끌 필요가 없습니다. – aha

0

스프링 보안은 캐싱 헤더를 비활성화합니다.

# Comma-separated list of paths to exclude from the default secured 
security.ignored= /someUrl1 

docs

0

에 대한 자세한 내용보기 : - 당신을 확보 할 필요가없는 일부 동적 응답을 가지고 있고 당신이 그들을 캐시 HTTP 헤더를 사용하려면 그냥 당신의 application.property 경로입니다 나는 비슷한 문제에 부딪친 다. 브라우저에 캐시 된 동적 리소스 (이미지)를 얻고 싶었습니다. https://github.com/foo4u/spring-mvc-cache-control : 이미지 변경 (안 매우 자주) 나는 URI의 일부를 변경하는 경우 ...이 내가이 스프링 확장을 발견 내 sollution

http.headers().cacheControl().disable(); 
    http.headers().addHeaderWriter(new HeaderWriter() { 

     CacheControlHeadersWriter originalWriter = new CacheControlHeadersWriter(); 

     @Override 
     public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { 
      Collection<String> headerNames = response.getHeaderNames(); 
      String requestUri = request.getRequestURI(); 
      if(!requestUri.startsWith("/web/eventImage")) { 
       originalWriter.writeHeaders(request, response); 
      } else { 
       //write header here or do nothing if it was set in the code 
      }  
     } 
    }); 
+1

코드는 다음과 같이 짧게 할 수 있습니다 : http.headers(). cacheControl(). disable(); . http.headers() addHeaderWriter (새 DelegatingRequestMatcherHeaderWriter ( 새로운 NegatedRequestMatcher (새 AntPathRequestMatcher ("/ 웹/eventImage")), 새로운 CacheControlHeadersWriter() 는));' – yankee

2

입니다.

3 단계 만 수행하면됩니다.

1 단계 (pom.XML) :

<dependency> 
    <groupId>net.rossillo.mvc.cache</groupId> 
    <artifactId>spring-mvc-cache-control</artifactId> 
    <version>1.1.1-RELEASE</version> 
    <scope>compile</scope> 
</dependency> 

2 단계 (WebMvcConfiguration.java) :

@Configuration 
public class WebMvcConfig extends WebMvcConfigurerAdapter implements WebMvcConfigurer { 
    @Override 
    public void addInterceptors(InterceptorRegistry registry) { 
     registry.addInterceptor(new CacheControlHandlerInterceptor()); 
    } 
} 

3 단계 (컨트롤러) :

@Controller 
public class MyRestController { 

    @CacheControl(maxAge=31556926) 
    @RequestMapping(value = "/someUrl", method = RequestMethod.GET) 
    public @ResponseBody ResponseEntity<String> myMethod(
      HttpServletResponse httpResponse) throws SQLException { 
     return new ResponseEntity<String>("{}", HttpStatus.OK); 
    } 
} 
2
@Configuration 
@EnableAutoConfiguration 
public class WebMvcConfiguration extends WebMvcConfigurerAdapter { 

    @Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry) { 

     registry.addResourceHandler("/resources/**") 
       .addResourceLocations("/resources/") 
       .setCachePeriod(31556926); 

    } 
} 
+2

이 정적 리소스만을위한 것입니다. –

관련 문제