0

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??

Shanka Somasiri
  • 581
  • 1
  • 8
  • 30
  • did you try @Requestparam List ? – Ashrik Ahamed May 30 '23 at 04:31
  • 1
    You cant. RequestParam does not work on complex objects, only Strings. So you can have a List for all sortBy, and List for all sortDirection. There might be other ways, see https://stackoverflow.com/questions/33354534/spring-mvc-requestparam-a-list-of-objects – JCompetence May 30 '23 at 07:12

1 Answers1

0

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);
    }
Shanka Somasiri
  • 581
  • 1
  • 8
  • 30