Spring Controller:将查询参数绑定到自定义POJO字段

问题描述 投票:0回答:1

我正在尝试将请求查询参数中的某些值映射到POJO参数,如下所示。这是POJO:

import lombok.*;
import org.springframework.format.annotation.DateTimeFormat;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.Map;

@Data
@Builder
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Person {
    @NotNull(message = "personId cannot be null")
    @Min(value = 0)
    private Long personId;

    @NotNull(message = "from date cannot be null")
    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
    private LocalDateTime from;

    @NotNull(message = "to date cannot be null")
    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
    private LocalDateTime to;

    private Map<String, String> filters;
}

这是控制器:

    @GetMapping(path = "/persons")
    public ResponseEntity<Integer> getPersons(@Valid final Person personRequest) throws Exception {
        return ResponseEntity.ok(personService.getPersonsCount(personRequest));
    }

我想将请求查询参数映射到此pojo的属性。这是预期的请求:

{application_url}/persons?personId=12&from=2017-03-22T00:00:00&to=2019-03-22T00:00:00&country=UK&company=xyz

我想将personId, from, to映射到POJO中的相应属性,并将其余查询参数nationality, company映射到过滤器映射。换句话说,personId, to, from在请求中只是静态的,其余参数可能有所不同,我们可以使用salary=1000&minAage=31代替country=UK&company=xyz,因此我想将其余参数映射到filters映射。 >

有没有办法做到这一点?

我正在尝试将请求查询参数中的某些值映射到POJO参数,如下所示。这就是POJO:import lombok。*;导入org.springframework.format.annotation.DateTimeFormat; ...

java spring pojo http-request-parameters
1个回答
0
投票

您可以通过将@RequestParam Map<String, String> filters与其他请求参数一起使用,或仅将map用于请求参数来实现。因为所有参数都将包含在地图中。

© www.soinside.com 2019 - 2024. All rights reserved.