【问题标题】:Spring RepositoryRestResource response only if specific headers exist仅当存在特定标头时才响应 Spring RepositoryRestResource
【发布时间】:2018-07-10 12:15:31
【问题描述】:

只有当 mime-type 为 application/json 时,我如何才能指定 @RepositoryRestResource 指向响应?

@RequestMapping 示例

带有Accept : application/json 的GET-Request 返回json

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

不带Accept : application/json 标头的GET-Request 返回html

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

【问题讨论】:

    标签: java json spring rest spring-boot


    【解决方案1】:

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

    @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");
          }
        };
      }
    }
    

    【讨论】:

    • 这会将响应媒体类型设置为 application/json。正确的?但是,如果客户端无法处理 json,我希望忽略整个请求。所以 Spring RepositoryRest 只有在客户端用 application/json 表示 Accept 标头时才应该响应!
    猜你喜欢
    • 2022-12-15
    • 2015-10-08
    • 2019-11-04
    • 2022-08-22
    • 2013-01-10
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多