Issue
I have this form:
<form action="/my-path" method="post">
<div class="form-group">
<label for="domain">Domain</label>
<input class="form-control" id="domain" type="text" value="" name="domain">
<label for="color">Color</label>
<input class="form-control" id="color" type="text" value="" name="color">
</div>
<button class="btn btn-primary" type="submit">Filter</button>
</form>
which I'm trying to process in Spring MVC:
@PostMapping(
path = ["/my-path"],
produces = [MediaType.TEXT_HTML_VALUE])
public ResponseEntity<String> doSomething(ModelMap map) {
// ...
}
but I just can't get this working, I see no data coming from the POST
even when I fill the form with data and submit it.
I tried binding the values to my own dto:
@PostMapping(
path = ["/my-path"],
produces = [MediaType.TEXT_HTML_VALUE])
public ResponseEntity<String> doSomething(@RequestBody MyDto dto) {
// ...
}
but in this case I get an exception because the method is unsupported (url encoded form). I'm at a loss here, I've tried 10 different ways to get the form data out of the request but it doesn't work, I either get exceptions or I get no data at all.
How do I make this pretty basic use case working with Spring Boot?
Solution
If you want to get all the request parameters in a map, you can add a @RequestParam
Map parameter to the function, like this:
@PostMapping(
path = ["/my-path"],
produces = [MediaType.TEXT_HTML_VALUE])
public ResponseEntity<String> doSomething(@RequestParam Map allRequestParams) {
// ...
}
If you want to get each form component in a different variable, you could use something like this:
@PostMapping(
path = ["/my-path"],
produces = [MediaType.TEXT_HTML_VALUE])
public ResponseEntity<String> doSomething(String domain, String color) {
// ...
}
Spring automagically will bind the form inputs to your parameters matching the inputs 'id' attribute with the parameter names.
Answered By - jdmuriel