Home » Java » How can i update cache-control header in http response for all api based on annotation in spring-boot application

How can i update cache-control header in http response for all api based on annotation in spring-boot application

Posted by: admin June 30, 2018 Leave a comment

Questions:

I want to update default cache-control header in HTTP response for all API based on annotation in the spring-boot application.

I have used Filter interceptor and it works but I’m looking for some specific feature for same.

Cache Annotation

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface Cache {

   int maxAge() default 4500;

   long sMaxAge() default -1;
}

Interceptor class

public class ResponseHeader implements Filter {

    private ApplicationContext appContext;

    public ResponseHeader(ApplicationContext appContext) {
        super();
        this.appContext = appContext;
    }

   @Override
   public void destroy() {
     // TODO Auto-generated method stub

   }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
          HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        ServletResponseWrapperCopier capturingResponseWrapper = new ServletResponseWrapperCopier(
            httpServletResponse);
        chain.doFilter(request, capturingResponseWrapper);
        try {
            RequestMappingHandlerMapping req2HandlerMapping = (RequestMappingHandlerMapping) appContext
                .getBean("requestMappingHandlerMapping");
            HandlerExecutionChain handlerExeChain = req2HandlerMapping.getHandler((HttpServletRequest) request);
            if (Objects.nonNull(handlerExeChain)) {
                Method method = ((HandlerMethod) handlerExeChain.getHandler()).getMethod();
                if (method.isAnnotationPresent(Cache.class)) {
                    Cache cacheControlAnnotation = method.getAnnotation(Cache.class);
                CacheControl cacheControl = 
CacheControl.maxAge(cacheControlAnnotation.maxAge(), TimeUnit.SECONDS).cachePublic()
                        .sMaxAge(cacheControlAnnotation.sMaxAge(), TimeUnit.SECONDS);

     httpServletResponse.setHeader(HttpHeaders.CACHE_CONTROL, 
 cacheControl.getHeaderValue());
                } 
            }
        } catch (Exception e) {
           // TODO: handle exception
        }

    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
       // TODO Auto-generated method stub

    }
}
Answers: