How to enable HTTP response caching in Spring Boot

前端 未结 8 1795
我寻月下人不归
我寻月下人不归 2020-11-27 12:17

I have implemented a REST server using Spring Boot 1.0.2. I\'m having trouble preventing Spring from setting HTTP headers that disable HTTP caching.

My controller is

相关标签:
8条回答
  • 2020-11-27 13:19

    I run into similar problem. I wanted to get just some of dynamic resources (images) cached in the browser. If image changes (not very often) I change the part of uri... This is my 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
                }       
            }
        });
    
    0 讨论(0)
  • 2020-11-27 13:19

    I used below lines in my controller.

    ResponseEntity.ok().cacheControl(CacheControl.maxAge(secondWeWantTobeCached, TimeUnit.SECONDS)).body(objToReturnInResponse);
    

    Please note that Response will have header Cache-Control with value secondWeWantTobeCached. However if we are typing url in addressbar and pressing enter, Request will always be sent from Chrome to server. However if we hit url from some link, browser will not send a new request and it will be taken from cache.

    0 讨论(0)
提交回复
热议问题