How to set/get values of checkboxes from a servlet dynamically

imgr8 picture imgr8 · Jul 24, 2011 · Viewed 40.9k times · Source

This is more of a logic question. I have a checkbox on a webpage and I store its value from the servlet request parameters in a Boolean object (Java). The logic is, if the request parameter for the checkbox is not null, make the object true, otherwise it's null. When the page is called again, it marks the checkbox as "checked" if its stored value is true.

this.checkbox = (servlet.getParameter("checkbox")!=null && servlet.getParameter("checkbox").contentEquals("on"))?true:null;

The problem starts when I persist that checkbox object. I first populate the page with the persisted data and then fill it with the servlet values. If the checkbox value is stored as true in the database, and the user unchecks it on the page and submits it, since the servlet parameter for the checkbox becomes null, I am unable to make the checkbox null. So the checkbox always show the persisted value since its never gets overwritten. So can anyone suggest some logic change in how I am filling the object value?

Answer

Alexander Pogrebnyak picture Alexander Pogrebnyak · Jul 24, 2011

The only valid test for checkbox is to see whether getParameter() returns null or not.

If the return value is null it's unchecked, otherwise it's checked.

Note, that checked attribute should be present if you want the checkbox be checked on the first page presentation and should not be present at all if you want it unchecked. The parameter value should always be checked, as in the example below.

<label>
  <input
    type="checkbox" 
    id="cb_id"
    name="cb_id"
    value="cb_id_value"
    checked="checked"
  />
  My label
</label>

For this example, you may have this logic in your servlet processing code:

HTTPServetRequest request = ...;

boolean cbState = request.getParameter( "cb_id" ) != null;

Note, that if the checkbox is checked by the user in the above example getParameter will return "cb_id_value", but because you usually have a single checkbox with a dedicated name you don't have to check the value.

BTW, I've noticed in your example that you are using servlet to getParameter. I hope that in your system it is a moniker for HTTPServletRequest.