Home > Net >  Parsing query parameters that contains square brackets in spring boot as a map
Parsing query parameters that contains square brackets in spring boot as a map

Time:10-22

I am currently working on rewriting the backend of a PHP Symfony application with Spring boot. I cannot touch the front-end code, and have to modify my backend to work in accordance with existing request structure. However, I am currently stuck with something that i need some help with

some examples of an endpoint looks as below

/app/api/incidents?customSearch=Some reason&dt=month&order[timeStart]=desc
/app/api/incidents?customSearch=Some reason&dt=month&order[timeResolved]=desc

How can I map these endpoints to my RestController as a Map ? as per latest tomcat configuration square brackets are not valid and hence unsupported, throwing a 400 error. Adding a configuration for tomcat to support these characters, resolves the issue. But how can I map the above request params into an order hashmap ? There are other parameters that needs to be mapped as well e.g. timeStart

/app/api/incidents?timeStart[after]=2022-10-11 00:00:00&timeStart[before]=2022-10-13 23:59:59&dt=range&order[incidentSeverity.orderBy]=desc

based on these values, the corresponding query needs to be formed.

    @GetMapping
    public ResponseEntity<String> test(@RequestParam(name = "order") Map<String, String> order) {
        log.info("order : "   order);
        return ResponseEntity.ok("Hello");
    }

But order is mapped to null

Can anyone please help me with this. I have already wasted way more time than I should have.

CodePudding user response:

I believe that's because of name in (@RequestParam(name = "order"). Spring boot tries to bind a request parameter named order when you put name not the whole map. You should remove nameto accept all parameters to a map.

   @GetMapping
   public ResponseEntity<String> test(@RequestParam Map<String, String> order) {
       log.info("order : "   order);
       return ResponseEntity.ok("Hello");
   }

CodePudding user response:

The problem should not be the code you have but the url that you send that is broken in an earlier place

/app/api/incidents?customSearch=Some reason&dt=month&order[timeStart]=desc

Try with

/app/api/incidents?customSearch=Some reason&dt=month&order[timeStart]=desc

you should normally encode empty spaces in query parameter values.

  • Related