sumit badaya sumit badaya - 5 months ago 25
HTML Question

Passing array of String in html form and submit to Java Spring Controller?

I'm having a hard time figuring out how to pass an array of values to a java spring controller method in RequestParam.

My html form is below:

<form method="post">
<input type="text" name="numbers[]">
<input type="submit">
</form>


and my spring controller is as follows:

@RequestMapping(value="/send", method = RequestMethod.POST)
public void sendMessage(String to[]) {
for(String number: to) {
System.out.println(number);
}
}


However when I run this, it shows an error:


... is not applicable for the arguments

Answer

The problem is that your input is merely a String field, so Spring converts it as a String, not as an array of String.

A solution is to have several inputs in your form with the same name. Spring automatically creates the array and passes it to the controller as such.

<form method="post">
  <input type="text" name="number">
  <input type="text" name="number">
  <input type="text" name="number">
  <input type="submit">
</form>

The corresponding method in the controller would be:

public void foo(@RequestParam("number[]") List<String> to) {
    for(String number : to) {
        System.out.println(number);
    }
}