-1

Is there a way to get all request parameters in Java Spring? For example, in DJango you can do something like:

def view(request):
    print request.META

And from that you can see the GET or POST parameters that are sent, which is helpful for debugging. The only way I've seen to do this so far is by specifying the specific parameter, such as @RequestParam(name="hello")

R. Karlus
  • 2,094
  • 3
  • 24
  • 48
David542
  • 104,438
  • 178
  • 489
  • 842

1 Answers1

2

The answer is yes! You can do this by injecting the HttpServletRequest object in your endpoint by simple doing:

@RequestMapping(value="/foo")
public String bar(HttpServletRequest request){
    System.out.println("Here you can see the creation time: " + request.getSession().getCreationTime());
    return "whatever string"; 
}

Then you can do just as following to list your parameters: Get servlet parameters

Improving it (suggestion from @BoristheSpider) you can use the MultiValueMap<String, String> object that already maps all of your parameters into one object. So you can do something like this:

@RequestMapping(value="/foo")
public String bar(@RequestParam MultiValueMap<String, String> parameters){ ... }

You can see an usage in here.

R. Karlus
  • 2,094
  • 3
  • 24
  • 48
  • 2
    Why not autowire a `MultiValueMap`? This seems to somewhat defeat the object of using Spring... – Boris the Spider Jul 02 '18 at 20:45
  • 3
    @BoristheSpider do you mean using a `@RequestParam MultiValueMap`? It will do the same internally. No problem with that :) – R. Karlus Jul 02 '18 at 20:48
  • 2
    Many things will do the same internally - the point is to leverage the framework to do those things rather than do them yourself. That is literally the purpose of using a framework like Spring. – Boris the Spider Jul 02 '18 at 20:48
  • @Rhuan -- thanks for this. How would I then access a GET param, such as `request.get("hello")`? – David542 Jul 02 '18 at 20:50
  • To access this param you don't need to list all params @David542, you just need to add the parameter itself to your method, supposing that it's a String: `@RequestParam(name = "hello") String hello`. It will look like: `public String bar(@RequestParam(name = "hello") String hello) { ... }` – R. Karlus Jul 02 '18 at 20:53
  • To get the parameter off the request class, use `String name = request.getParameter("name")`. – David542 Jul 02 '18 at 20:53
  • @BoristheSpider my fault, you're totally right! Do you think I should correct my answer? – R. Karlus Jul 02 '18 at 20:54
  • Maybe just expand on it, add in the other options as to how to achieve the result. – Boris the Spider Jul 02 '18 at 20:55