【问题标题】:SpringBoot – add Cache Control Headers in Rest methodsSpring Boot – 在 Rest 方法中添加 Cache Control Headers
【发布时间】:2018-10-15 06:47:22
【问题描述】:

我有一个基本的 SpringBoot 2.0.5.RELEASE 应用程序。使用 Spring Initializer、JPA、嵌入式 Tomcat、Thymeleaf 模板引擎,并打包为可执行 JAR

我已经创建了这个 Rest 方法:

  @GetMapping(path = "/users/notifications", consumes = "application/json", produces = "application/json")
    public ResponseEntity<List<UserNotification>> userNotifications(
            @RequestHeader(value = "Authorization") String authHeader) {

        User user = authUserOnPath("/users/notifications", authHeader);

        List<UserNotification> menuAlertNotifications = menuService
                .getLast365DaysNotificationsByUser(user);

        return ResponseEntity.ok(menuAlertNotifications)
                .cacheControl(CacheControl.maxAge(60, TimeUnit.SECONDS));;

    }

我想添加一个缓存控制标头,但我不知道如何... 我得到一个编译错误:

Multiple markers at this line
    - The method cacheControl(CacheControl) is undefined for the type 
     ResponseEntity<List<UserNotification>>
    - CacheControl
    - cacheControl

我也在application.properties中添加了这个属性

security.headers.cache=false

【问题讨论】:

  • 你在使用spring security吗?
  • 是的,我正在使用 Spring Security

标签: java rest spring-boot http-headers resttemplate


【解决方案1】:

当您使用ResponseEntity.ok(T body) 时,返回类型为ResponseEntity&lt;T&gt;,因为它是将数据添加到ResponseEntity 的正文部分的快捷方法。

您需要通过 ResponseEntity.ok() 创建的构建器对象,没有返回 Builder 对象的参数。然后,您可以通过 body 方法自己添加数据。

所以你的代码应该是这样的

  @GetMapping(path = "/users/notifications", consumes = "application/json", produces = "application/json")
    public ResponseEntity<List<UserNotification>> userNotifications(
            @RequestHeader(value = "Authorization") String authHeader) {

        User user = authUserOnPath("/users/notifications", authHeader);

        List<UserNotification> menuAlertNotifications = menuService
                .getLast365DaysNotificationsByUser(user);


        return ResponseEntity.ok().cacheControl(CacheControl.maxAge(60, TimeUnit.SECONDS)).body(menuAlertNotifications);


    }

【讨论】:

    猜你喜欢
    • 2016-01-17
    • 1970-01-01
    • 1970-01-01
    • 2020-09-03
    • 2011-03-04
    • 2020-09-15
    • 2020-02-14
    • 2021-02-11
    • 1970-01-01
    相关资源
    最近更新 更多