How do you set cache headers in Spring MVC?

后端 未结 10 1065
名媛妹妹
名媛妹妹 2020-12-04 09:23

In an annotation-based Spring MVC controller, what is the preferred way to set cache headers for a specific path?

10条回答
  •  半阙折子戏
    2020-12-04 09:49

    Starting with Spring 4.2 you can do this:

    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 getPermissions() {
    
            MyDto body = new MyDto();
    
            return ResponseEntity.ok()
                .cacheControl(CacheControl.maxAge(20, TimeUnit.SECONDS))
                .body(body);
        }
    }
    

    CacheControl object is a builder with many configuration options, see JavaDoc

提交回复
热议问题