2

I am new to JSP, and i want to make a simple crud application. I want to save a Meal, wich consists of a number of ingredients, the problem is that you don't know how many.

I have this code within a <form action="Controller" method=POST">.

The fault in the current code is that that HTTPServletRequest will only know that last checkbox, since all the checkboxes have the same 'name'. But as I don't know the number of ingredients the user will add i cannot number them accordingly. Is there a way to send a List to my controller ?

                                <%
                                    List<Ingredient> ingredients = (List) request.getAttribute("ingredients");
                                %>
                                <div class="btn-group" data-toggle="buttons">
                                    <% for (Ingredient ingredient : ingredients) {%>
                                    <label class="btn btn-primary">
                                        <input type="checkbox" name="SelectedIngredients" value="<%=ingredient.getName()%>"><%=ingredient.getName()%>
                                    </label>                                      
                                    <% }%>
                                </div>
MrMe TumbsUp
  • 416
  • 1
  • 4
  • 17

2 Answers2

1

You should use getParameterValues().

See: http://www.coderanch.com/t/603190/Servlets/java/Retrieve-array-parameters-request

dreamwagon
  • 1,219
  • 1
  • 15
  • 17
0

You must simply use request.getParameterValues("SelectedIngredients") to get all the checked ingredients, as a String[].

Please read How to avoid using scriptlets in my JSP page?.

Community
  • 1
  • 1
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255