java - 仅当特定 header 存在时,Spring RepositoryRestResource 响应

标签 java json spring rest spring-boot

如何指定 @RepositoryRestResource 仅在 mime-type 为 application/json 时指定响应?

@RequestMapping 示例

GET-Request with Accept : application/json 返回 json

 @RequestMapping(path="/path", headers ="Accept=application/json")
    public String withHeader() {
        return  "{this:json}";
    }

没有 Accept : application/json header 的 GET-Request 返回 html

@RequestMapping("/path" )
public String withoutHeader() {
    return  "<html>...</html>";
}

最佳答案

您无法开箱即用。您需要添加这样的配置

@Configuration
class RestMvcConfiguration {

  @Bean
  public RepositoryRestConfigurer repositoryRestConfigurer() {

    return new RepositoryRestConfigurerAdapter() {

      @Override
      public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
        config.returnBodyOnUpdate("Accept=application/json")
        config.returnBodyOnCreate("Accept=application/json");
      }
    };
  }
}

关于java - 仅当特定 header 存在时,Spring RepositoryRestResource 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48541279/

相关文章:

java - 使用 lambda 函数对数组列表进行排序不起作用

python - 无法使用 Python 将 JSON 文件转换为 CSV

ruby-on-rails - Rails 无法将 JSON 识别为响应类型

java - 存在可选长参数 'id',但无法转换为空值

spring - JPA 事务未提交到数据库

java - Spring Data Rest 导致 GC 开销超出

java - 如何将小数点舍入到小数点后两位(Java)

java - 非 Java JVM 语言 - Java 语言未利用的任何特定 JVM 功能

json - 单元测试 JSON Swift

c# - 从 C# 调用 Java Servlet