Extracting Request Parameters Dynamically for a application/x-www-form-urlencoded Request in Spring

While working on my Micropub endpoint I found that I needed to support application/x-www-form-urlencoded requests.

I had to dynamically parse these fields out because on any given request there could be anywhere between 4 and 10 parameters in a given request, and I'd not really ever know what that request would look like until receiving it.

I found that Spring has you covered, and makes this quite convenient, simply asking you to amend your endpoint to request a MultiValueMap. Remember to mark it as the @RequestBody, otherwise Spring won't know where those parameters are coming from:

import org.springframework.util.MultiValueMap;

@PostMapping(path = "/endpoint", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<String> form(@RequestBody MultiValueMap<String, String> formParameters) {
  // iterate through `formParameters` as you wish

  // get all values for a given parameter
  List<String> contentValues = formParameters.get("content");

  // get the first instance for a given parameter
  String content = formParameters.getFirst("content");

This has been tested with Spring Boot 2.1.4.RELEASE (which contains Spring 5.1.6.RELEASE).

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #java #spring.

This post was filed under articles.

Related Posts

Other posts you may be interested in:

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.