<form> checkbox submit to servlet


I was wondering how this can be done:

I have an html page and <form> tag in it.
I have <input> tags and get its values in a servlet like this: request.getParameter(“name”);

I need to put 3 check boxes in html page. In a servlet I need to check which box is selected. According to selection do something.


When your form is sent into the servlet you grab your checkbox values just like anything else. In other words you have these checkboxes:

<input type='checkbox' name='some' value='do' />
<input type='checkbox' name='some_more' value='dont' />
<input type='checkbox' name='even_more' value='try' />

In your servlet you just grab the variables like you would anything else:

String checkBox = "";

if (res.getParameter("some") != null && res.getParameter("some").trim().length != 0) {
  checkBox = res.getParameter("some").trim();
else if (res.getParameter("some_more") != null && res.getParameter("some_more").trim().length != 0) {
  checkBox = res.getParameter("some_more").trim();

etc etc …


I’ll try it out.


Also remember that if you only want your clients to choose one of the checkboxes … make them radio buttons. That will make your servlet testing a whole lot easier!

Thanks, I actually decided to use them and have been looking at this:

<input checked name=“cost” type=“radio”/>
<input type=“radio” name=“cost”/>
<input type=“radio” name=“cost”/>

I need to have a group of 3 radio buttons and one of them has to be selected at all times. To create a group I need to use the same name for all of them.

If i use the same name than how do I get its value in a servlet?

same way you get any other parameter


will return the one you’ve selected, except you need to give them values like:

<input checked name="cost" type="radio" value="1"/>
<input type="radio" name="cost" value="2"/>
<input type="radio" name="cost" value="3"/>

The getParam will return 1, 2 or 3 depending on the selection

ok, thanks!