I am having a checkbox in html like this :
<input type="checkbox" name="subscribe" value="subscribe">Subscribe For Answers</input>
And in my servlet i get its value by doing something like this :
String checked=new String();
checked=request.getParameter("subscribe");
if(!checked.isEmpty()){
if(checked.compareTo("subscribe")==0)
{
ps.setInt(4, 1);
}
}
else {
ps.setInt(4,0);
}
But if checkbox is not checked then it gives Null Pointer Exception.Please help to correct it.
If the checkbox is not checked, the request won't contain any subscribe
parameter, so checked
will be null
. You want something like:
String checked = request.getParameter("subscribe");
if (checked != null && !checked.isEmpty()) {
...
} else {
...
}
As an aside, do you really want to not call ps.setInt(4, ...)
at all if the parameter value is provided, but isn't "subscribe"? Currently, you've got three options:
(It's also not clear why you're using String.compare
rather than String.equals
...)
See more on this question at Stackoverflow