提问者:小点点

偏移和限制在GET中不起作用API


我有一个Spring应用程序。

我的获取api:

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

 @GetMapping(path = {"/v1/Log"},
        produces = {"application/json"},
        consumes = {"application/json"})
public ResponseEntity<LogsResponse> getLog(final Pageable pageable) {
        final Page<Log> log = LogService.getActionLog(pageable);
        return ResponseEntity.ok(log.content);
}

我的存储库类:

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface LogDBRepository extends MongoRepository<Log, String> {
    Page<Log> findAll(final Pageable pageable);
}

这就是我测试偏移和限制的方式:

我面临的问题是-

当相同的api工作如果我使用 /log?页=1

我的期望:如何使它只返回1个结果并跳过第一个结果?


@Test
public void givenPageRequest_whenGetLogCalled_returnSuccess() {

LogDBRespository.saveAll(Arrays.asList(Log.builder().id("id1").transactionId("tx1").status(LogStatus.PENDING).build(),
                Log.builder().id("id2").status(LogStatus.PENDING).transactionId("tx2").build()));

final HttpHeaders headers = new HttpHeaders();
        
headers.setContentType(MediaType.APPLICATION_JSON);

final HttpEntity httpEntity = new HttpEntity(headers);

ResponseEntity<LogsResponse> responseEntity = testRestTemplate.exchange("/log?offset=1&limit=1", HttpMethod.GET, httpEntity, LogsResponse.class);

Assertions.assertEquals(HttpStatus.OK.value(), responseEntity.getStatusCode().value());

}

共2个答案

匿名用户

如果您尝试将请求参数中的值绑定到可分页,您必须使用在可分页(或更具体地说是PageRequest)中定义的相同变量,即pagesize

这就是为什么当你使用页面和大小时,它会起作用。

但是,如果您在请求参数中使用其他名称传递这些值,则必须这样做,

public ResponseEntity<LogsResponse> getLog(@RequestParam(defaultValue = "0") Integer offset, @RequestParam(defaultValue = "10") Integer limit) {
    Pageable pageable = PageRequest.of(offset, limit);
    
    final Page<Log> log = LogService.getActionLog(pageable);
    return ResponseEntity.ok(log.content);
}

匿名用户

我不是分页方面的专家,但我认为如果您不使用默认参数“page”和“size”,则必须自己创建使用请求参数的可分页对象。目前,这些参数根本不会被您的控制器方法使用。因此,使用参数在控制器中创建您自己的可分页对象:

@GetMapping(path = {"/v1/Log"},
    produces = {"application/json"},
    consumes = {"application/json"})
public ResponseEntity<LogsResponse> getLog(@RequestParam(value = "offset", required = false) Integer offset, @RequestParam(value = "limit", required = false) Integer limit) {
    //A check for null values in the request params would be a good idea here
    PageRequest pageRequest = new PageRequest(offset, limit, Direction.DESC);
    final Page<Log> log = LogService.getActionLog(pageRequest);
    return ResponseEntity.ok(log.content);
}

如果使用不带值的@Request estParam,Spring mvc期望参数名等于变量名,在这种情况下可以省略值表达式。如果省略必填表达式,则默认为true,这意味着如果缺少参数,则请求失败。

另一种方法是覆盖分页的默认参数名称,请参阅本教程。