【问题标题】:Validate Spring Hateoas Pageable param验证 Spring Hateoas Pageable 参数
【发布时间】:2016-03-31 12:09:28
【问题描述】:

我应该如何在 Spring Hateoas 中有效的 Pageable 参数? IE。我有简单的场景(使用 Spring-Data-Elasticsearch):

public class Entity {
    private long timestamp;

    public long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(long timestamp) {
        this.timestamp = timestamp;
    }
}

    @Autowired
    private EntitiesRepository repository

    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<PagedResources<Resource<Entity>>> list(Pageable pageable, PagedResourcesAssembler<Entity> assembler){
        Page<Entity> entities = repository.findAll(pageable);
        PagedResources<Resource<Entity>> pagedResources = assembler.toResource(entities);
        return new ResponseEntity<PagedResources<Resource<Entity>>>(pagedResources, HttpStatus.OK);
    }

如果我将有效值传递给排序参数,即localhost:8080/app/list?sort=timestamp,则一切正常,但如果值错误(给定属性不存在),即localhost:8080/app/list?sort=name,则抛出弹性搜索异常:

org.elasticsearch.action.search.SearchPhaseExecutionException

所以,我的问题是:添加 Pageable 参数验证有什么好的做法吗?

【问题讨论】:

    标签: java spring validation elasticsearch spring-hateoas


    【解决方案1】:

    我一直在寻找一种方法来验证 Pageable 或 Sort 实例,但看起来这些实例无法使用 @Valid 或 @Validated 进行验证,即使使用您自己的验证器也是如此。 Spring 根本不会在这些特定参数上调用 validate()。

    我想执行验证的唯一方法是扩展 PageableArgumentResolver 或 PageableHandlerMethodArgumentResolver 以包含缺少的验证逻辑。

    【讨论】:

      猜你喜欢
      • 2016-09-11
      • 1970-01-01
      • 2017-09-11
      • 2020-02-07
      • 1970-01-01
      • 1970-01-01
      • 2014-04-03
      • 2015-03-17
      • 1970-01-01
      相关资源
      最近更新 更多