1

I am trying to catch other query parameters to a Map<String,String> ex : http://url.example/route?lastIndex=10&sort=-afield&othera=test&otherb=test I want othera and otherb to be stored in a map. Is it possible ?

class MyRequest {
   private String lastIndex;
   private String sort;
   private Map<String,String> myFilters;
}

@RestControler
class MyController {
   @GetMapping("/route")
   public String get(MyRequest request) {
     return "OK";
  }
}
kukkuz
  • 41,512
  • 6
  • 59
  • 95
Lombric
  • 830
  • 2
  • 11
  • 23

2 Answers2

0

I don't think so it may work if you are going to use MyRequest class. Given that these are AJAX GET requests (since its a @RestController), you can use @RequestBody:

@RestControler
class MyController {
   @GetMapping("/route")
   public String get(@RequestBody MyRequest request) {
     return "OK";
  }
}

and send the request as JSON like this instead of using query parameters:

curl -X GET \
  http://url.example/route/ \
  -H 'Content-Type: application/json' \
  -d '{
  "lastIndex": "var",
  "sort": "there",
  "myFilters":{
    "hello": "there",
    "hello1": "there1"
  }'
}

Can GET requests have body?

The specs are a bit ambiguous about it - you can read more on it here. But Spring Boot runtime containers (I checked Tomcat, Jetty and UnderTow in Spring Boot 2.0.4.RELEASE) support them if you are using AJAX GET requests.

kukkuz
  • 41,512
  • 6
  • 59
  • 95
  • AJAX GET request with body work, I just tested in my spring boot app... because a `RestController` is used here, it *is* AJAX right – kukkuz Mar 04 '19 at 14:05
  • If it works or not depends on your browser and runtime used. As the specification is a bit ambiguous on it. See also https://stackoverflow.com/questions/978061/http-get-with-request-body – M. Deinum Mar 04 '19 at 15:19
  • It works in Spring Boot though, you can try it out :) It doesn't depend on the browser in any case ! – kukkuz Mar 04 '19 at 15:21
  • As stated that depends on the container. It might work on Tomcat, but when using Jetty/Netty/Undertow it might not work. – M. Deinum Mar 04 '19 at 15:22
  • @M.Deinum it works in Tomcat, Jetty & Undertow, these spring containers are supporting it... – kukkuz Mar 04 '19 at 15:37
  • Anyway, every time I do something in SO, it brushes up my knowledge... nice talking with you :) – kukkuz Mar 04 '19 at 15:39
0

As your MyRequset class contains only string parameters, it would be wise, probably to use something like

   @GetMapping("/route")
   public MyRequest get(@RequsetParam Map<String,String> allParams) 

and then just convert your parameters map the way you like.

Anatoly Tutov
  • 534
  • 7
  • 8