0

I am using @RequestParam to get the column name against which I want to sort my results.

public ResponseEntity<Map<String, Object>> method(@PathVariable("tenant_id") Integer tenantId,
                                                                             @PathVariable("asset_location_id") Integer assetLocationId,
                                                                             @RequestParam(defaultValue = "") String search_keyword,
                                                                             @RequestParam(defaultValue = "0") int page,
                                                                             @RequestParam(defaultValue = "10") int size,
                                                                             @RequestParam(defaultValue = "asset_name") String sort_field,
                                                                             @RequestParam(defaultValue = "asc") String sort_dir) {}

How I can make sure sort_field has the only possible column names which are possible in a given response?

itsaboutcode
  • 24,525
  • 45
  • 110
  • 156
  • You have write your own validator. Check this [answer](https://stackoverflow.com/a/59465567/19741639) – viking Nov 15 '22 at 17:39

1 Answers1

0

You can achieve this easily by using @ModelAttribute with @Valid annotation.

By using @ModelAttribute you can bind request parameters to dto, and then you just have to write method with validation and annotate it with @AssertTrue or @AssertFalse

Example code:

public ResponseEntity<Map<String, Object>> method(@PathVariable("tenant_id") Integer tenantId,
                                                  @PathVariable("asset_location_id") Integer assetLocationId,
                                                  @ModelAttribute @Valid FindTenantDto dto) {}

public class FindTenantDto {
    String searchKeyword;
    Integer page;
    Integer size;
    String sortField;
    String sortDir;
    
    @AssertTrue
    boolean isSortFieldAllowed(){
        // implement validation here
    }
}
KSs
  • 420
  • 3
  • 9