How to accept multiple Query parameters as a list of objects in Spring validation

54 Views Asked by At

I am using Springboot 2.7.9 and I need to invoke a Request as below

localhost:8081/api/projects?page=2&size=3&sortBy=projectName&sortDirection=desc&sortBy=startDate&sortDirection=asc

enter image description here

My PageSort entity is as below

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class PageSort {
    private String sortBy;
    @SortValueConstraint
    private String sortDirection;
}

How can I accept sortBy=projectName&sortDirection=desc&sortBy=startDate&sortDirection=asc as a List collection in my rest controller

@GetMapping
    public ResponseEntity<ApiResponseDTO> getProjects(
            @Valid ProjectPage projectPage,
            @Valid List<PageSort> sortList){
        return null;
    }

When I accept a single sort object (@Valid PageSort sortList) this perfectly works but when I introduce the list it doesn't work. I think it has to do something with the collections

Any ideas on this please??

1

There are 1 best solutions below

0
Shanka Somasiri On

Like mentioned by @JCompetence I was able to get this issue solved by the following code below.

@GetMapping
    public ResponseEntity<ApiPageResponseDTO> getProjects(
            @Valid CustomPage page,
            @Valid @RequestParam(value = "sortBy", required = false) List<String> sortByList,
            @Valid @RequestParam(value = "sortDirection", required = false) @SortValueConstraint List<String> sortDirectionList,
            @Valid ProjectSearchCriteria projectSearchCriteria){
        final List<PageSort> sortList = new ArrayList<>();
        validateSortByAndSortDirectionsList(page, sortByList, sortDirectionList, sortList);
        ApiPageResponseDTO projectResponseDTO = this.projectApi.getProjects(page, projectSearchCriteria);
        return new ResponseEntity<ApiPageResponseDTO>(projectResponseDTO, HttpStatus.OK);
    }