1

I am trying to combine multiple request parameters in a Map.

I could do it, but we want to restrict keys to some names, hence we defined an enum.

But the spring boot doesn't validate the Map. It just accepts, even if we send any key instead of the ones defined in the emum.

Ex:

@GetMapping("/name2")
    public void getList(@RequestParam Map<FilterEnum,String> map,
    @RequestParam(name = "Id", required = false) String Id) {...}
    public enum FilterEnum { 
        lifecyclestaus,
        name;
}

Request URL:

http://localhost:8090/employee/name2?bar=ks

Two issues:

  1. Ideally it should throw an error with the above request, as bar is not part of enum.
  2. Also the id request param should not be part of Map.

Thanks in advance.

Jagraj Singh
  • 4,031
  • 4
  • 15
  • 33
ashu
  • 579
  • 2
  • 6
  • 17
  • 1
    Technically none of your params will be populated based on the enum as the enums are all caps and query params are all small. If keys are already known then why not map it to DTO directly instead of an enum work around? https://stackoverflow.com/questions/16942193/spring-mvc-complex-object-as-get-requestparam – Mohammed Atif Jun 29 '22 at 06:14
  • @MohammedAtif, Perfect i could use DTO, but if we send other than DTO fields, those will be ignored. Cant we send exception saying request param is not supported or bad request validation? – ashu Jun 29 '22 at 06:23
  • 1
    Ideally it is not recommended as unknown query params are totally harmless but if you still want to enforce it then you can add an interceptor which I personally feel is an overkill until and unless it is an extreme requirement – Mohammed Atif Jun 29 '22 at 06:31
  • Also I noticed your employee id a request param instead of path param, is it intentional? – Mohammed Atif Jun 29 '22 at 06:33
  • yeah, just to showcase, that there are other params, other than DTO – ashu Jun 29 '22 at 06:52
  • passing resource id as request param still works but it is considered as bad design instead you must use path variable - https://www.baeldung.com/spring-pathvariable – Mohammed Atif Jun 29 '22 at 07:51

0 Answers0