0

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?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
vanita
  • 48
  • 4
  • 6
  • 1
    Why do you need such a function ? Dynamic forms are a bad idea in Java web programming since you cannot map the form with a Java bean. I'd rather preconize you a form with fields that can be hidden if you don't need them (with a dynamic "hidden" property and not a dynamic name). – Benoit Courtine Jul 23 '10 at 08:21
  • 1
    @Benoit: they are only a bad idea if you don't know what you're doing. – BalusC Jul 23 '10 at 12:50

1 Answers1

0

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:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555