Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 JHava 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

like image 281
jarvo69 Avatar asked Jul 08 '16 07:07

jarvo69


2 Answers

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);
    }
}
like image 53
Adrien Brunelat Avatar answered Sep 17 '22 16:09

Adrien Brunelat


If anyone is still struggling with that, this is how it should be done:

Form inputs:

<input name="myParam" value="1"/>
<input name="myParam" value="4"/>
<input name="myParam" value="19"/>

Controller method:

   @RequestMapping
    public String deletePlaces(@RequestParam("myParam") Long[] myParams) {

      //myParams will have 3 elements with values 1,4 and 19
    }

This works the same for String[] Integer[] Long[] and probably more. POST,GET,DELETE will work the same way.

Parameter name must match name tag from form input. No extra [] needed etc. In fact, param name can be ommited, if method argument name is the same as input name so we can end up with method signature like this:

   @RequestMapping
   public String deletePlaces(@RequestParam Long[] myParams) 

and it will still work

Something extra: Now if you have domain model lets say Place and you have PlaceRepository, by providing Place#id as value of your inputs, Spring can lookup related objects for us. So if we assume that form inputs above contais User ids as values, then we can simply write this into controller:

public String deletePlaces(@RequestParam Place[] places) {
  //places will be populated with related entries from database!
 }

Sweet isn't it?

like image 25
Antoniossss Avatar answered Sep 17 '22 16:09

Antoniossss