Spring MVC에서 캐시 헤더를 어떻게 설정합니까?
주석 기반 Spring MVC 컨트롤러에서 특정 경로에 대해 캐시 헤더를 설정하는 기본 방법은 무엇입니까?
저는 방금 같은 문제에 부딪혔고, 프레임워크에서 이미 제공한 좋은 해결책을 찾았습니다.org.springframework.web.servlet.mvc.WebContentInterceptor
class를 사용하면 기본 캐싱 동작과 경로별 재정의(다른 곳에서 사용된 것과 동일한 경로 일치 동작)를 정의할 수 있습니다.저를 위한 단계는 다음과 같습니다.
- 내 예를 확인합니다.
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter
에는 "cacheSeconds" 속성 집합이 없습니다. 의 인스턴스 추가
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
답은 매우 간단합니다.
@Controller
public class EmployeeController {
@RequestMapping(value = "/find/employer/{employerId}", method = RequestMethod.GET)
public List getEmployees(@PathVariable("employerId") Long employerId, final HttpServletResponse response) {
response.setHeader("Cache-Control", "no-cache");
return employeeService.findEmployeesForEmployer(employerId);
}
}
Code above shows exactly what you want to achive. You have to do two things. Add "final HttpServletResponse response" as your parameter. And then set header Cache-Control to no-cache.
기관.스프링 골조웹.서블릿버팀목이 되다모든 Spring 컨트롤러의 기본 클래스인 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);
콘텐츠를 생성하기 전에 컨트롤러 내에서 호출하거나 봄 컨텍스트에서 빈 속성으로 지정할 수 있습니다.
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 참조
Handler Interceptor를 사용하여 제공되는 postHandle 메서드를 사용할 수 있습니다.
postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
그런 다음 메소드에서 다음과 같이 헤더를 추가합니다.
response.setHeader("Cache-Control", "no-cache");
찾았습니다WebContentInterceptor
가장 쉬운 방법이 될 것입니다.
@Override
public void addInterceptors(InterceptorRegistry registry)
{
WebContentInterceptor interceptor = new WebContentInterceptor();
interceptor.addCacheMapping(CacheControl.noCache(), "/users", "admin");
registry.addInterceptor(interceptor);
}
이에 대한 주석을 정의할 수 있습니다.@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"
BTW: Spring MVC에서 캐시 제어를 기본적으로 지원한다는 것을 방금 알았습니다.Google 웹 콘텐츠인터셉터 또는 캐시 제어 처리기인터셉터나 캐시컨트롤이 있으면 찾을 수 있습니다.
이것이 정말 오래된 것이라는 것을 알지만, 구글링을 하는 사람들은 이것이 도움이 될 수 있습니다.
@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);
}
컨트롤러에서 응답 헤더를 직접 설정할 수 있습니다.
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
AnnotationMethodHandlerAdapter를 확장하여 사용자 지정 캐시 제어 주석을 찾고 그에 따라 http 헤더를 설정할 수 있습니다.
언급URL : https://stackoverflow.com/questions/1362930/how-do-you-set-cache-headers-in-spring-mvc
'programing' 카테고리의 다른 글
php 자동 증분이 9 또는 10000에서 중지됩니다. (0) | 2023.08.25 |
---|---|
코드백에서 RouteData에 액세스하려면 어떻게 해야 합니까? (0) | 2023.08.20 |
HomeBrew의 MariaDB: 네트워크 액세스 활성화 (0) | 2023.08.20 |
NSNotification 센터의 개체 속성을 사용하는 방법 (0) | 2023.08.20 |
nohup:입력을 취소하고 출력을 'up.out'에 추가합니다. (0) | 2023.08.20 |