tags:

views:

131

answers:

1

When I provide a dynamic name of checkbox inside a for loop like

<input type="checkbox" name="<%=i%>" />

How can I retrieve the value in servlet?

A: 

Three ways:

  1. Just rerun the same for loop in servlet as you did in JSP (you truly know the loop conditions) and do request.getParameter(i) on every iteration and if necessary add every parameter value to a List<String> so that you can easily process it afterwards.

  2. Prefix the parameter name with a certain string, e.g. name="foo${i}", grab all parameters by request.getParameterMap(), loop over it and determine if the name.startsWith("foo") and if necessary collect the matched values in a List<String>.

  3. Just give all checkboxes the same name, but a different value and grab the checked ones by request.getParameterValues("checkboxname");. It will return a String[] with all values.

Way 3 is the normal practice by the way.


That said, scriptlets (those <% %> things in your code) indicates bad practices. I'd suggest to throw away the old fashioned JSP/Servlet books/tutorials you're currently reading and get yourself through the following links to learn how to do things properly:

BalusC