Spring HTTP Cache Management

I saw that you can control the http cache headers using the AnnotationMethodHandlerAdapter bean.

My problem is that I need to have excellent cache control (at the method level). It would be best to have something like annotations like "@RequestCache (expire = 60)".

Is there anything similar? What is the best way to accomplish this task?

Thanks Andrea

Update: pap suggests using HandlerInterceptor, but I saw several forum posts saying that it is impossible to get the target method inside HandlerInterceptor and suggest using regular AOP instead (not specifically for caching). The problem is that I do not want to add a query parameter to all my methods, only to make it available to the aspect. Is there any way to avoid this?

+4
source share
2 answers

You can use the following approach described in Spring mvc reference

"Last-Modified" response header support to facilitate content caching

@RequestMapping(value = "/modified") @ResponseBody public String getLastModified(WebRequest request) { if (request.checkNotModified(lastModified.getTime())) { logger.error("Was not modified."); return null; } logger.error("Was modified."); //processing return "viewName"; } 
+3
source

One way (which I used myself) is to create your own HandlerInterceptor .

 public class CacheInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Class<?> o = AopUtils.getTargetClass(handler); if (o.isAnnotationPresent(RequestCache.class)) { response.setDateHeader("Expires", o.getAnnotation(RequestCache.class).expire()); } return true; } ... } 

and then

 <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"> <property name="interceptors"> <array> <bean class="bla.bla.CacheInterceptor " /> </array> </property> </bean> 
+2
source

Source: https://habr.com/ru/post/1399354/


All Articles