jumps4fun
jumps4fun

Reputation: 4132

How to post multiple <input type=“checkbox” /> as array to Java servlet?

This question is the same as How to post multiple <input type="checkbox" /> as array in PHP?, but I can't make the solution work in my java servlet setup. When using the apporach of adding a [] to the name property of the grouped checkboxes, I only get the first checked option. I am not sure if it is the actual posted array that is containing only one element, or if I'm not accessing it right server side. Here is what I do to check the value in java:

@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {  
    for(String name : request.getParameterMap().keySet()){      
        System.out.println(name +": " + request.getParameter(name));        
    }
}

this prints countries[]: US, even if I have more checboxes checked after the US-input. the value changes after which checkbox is the first of the checked ones. What am I doing wrong?

Here is my HTML:

<form action="mypage" method="post">
    <input id="cb-country-gb" type="checkbox" name="countries[]" class="hide" value="GB"/>
    <input id="cb-country-us" type="checkbox" name="countries[]" class="hide" value="US"/>
    <input id="cb-country-ge" type="checkbox" name="countries[]" class="hide" value="GE"/>
    <input id="cb-country-es" type="checkbox" name="countries[]" class="hide" value="ES"/>
    <button type="submit" class="btn btn-primary">Search</button>
</form>

Upvotes: 0

Views: 4418

Answers (2)

user987339
user987339

Reputation: 10707

You should use [getParameterValues][1] that returns an array of String objects containing all of the values the given request parameter has :

Test that with following code:

@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {  
    for(String name : request.getParameterMap().keySet()){
      for(String value : request.getParameterValues(name)){
          System.out.println(name +": " + value);        
      }
    }
}

Upvotes: 1

wero
wero

Reputation: 32980

If you check multiple checkboxes the request contains multiple parameters with name countries[].

If you call request.getParameter("countries[]") only the first parameter value is returned.

Instead you need to use

String[] checked = request.getParameterValues("countries[]");
if (checked != null)
     ...

Upvotes: 2

Related Questions