tags:

views:

35

answers:

2

HI, all

I have a problem of null pointer Exception in servlet . I have a form a.jsp with check box if I do not select this check box and submit form then null pointer exception is occur in a.servlet. How I Can handle this Exception

code a.jsp

<table border='0' width='50%' cellspacing='0' cellpadding='0' ><form name=form1 method=post action=aservlet >
<input type=hidden name=todo value=post>

<tr bgcolor='#ffffff'><td align=center >
<font face='verdana' size='2'><b>Sex</b><input type=radio name=sex value='male'>Male </font>
<input type=radio name=sex value='female'><font face='verdana' size='2'>Female</font></td></tr>

<tr><td align=center bgcolor='#f1f1f1'>
<font face='verdana' size='2'><input type=checkbox name=agree >I agree to terms and conditions </font>
</td></tr>

<tr bgcolor='#ffffff'><td align=center >
<input type=submit value=Submit>
 <input type=reset value=Reset>
</td></tr>
</form></table>

aservlet.java

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class Admin extends HttpServlet {
        public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException 
            {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
request.getParameter ("agree");
}}

Exception:

exception

java.lang.NullPointerException com.centralvisa.servlets.Admin.doPost(Admin.java:26) javax.servlet.http.HttpServlet.service(HttpServlet.java:637) javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

Thanks

A: 

When a checkbox is not selected, the request parameter for the checkbox, (in your case) 'agree' does not exist i.e. request.getParameter("agree") will return null.

If you assigned request.getParameter("agree") to some String variable, and then called a method on this String, you will get a NullPointerException.

Solution is to check for null before assigning the parameter value.

Simply

if (request.getParameter("agree") != null ){
    // do stuff

}
JoseK
A: 

Few information. Problably you are accessing the parameter without checking if it's sent.

Try with something like this in your servlet:

boolean checked=false;
if(request.getParameter("checkbox")!=null && 
   request.getParameter("checkbox").equals("checkbox_value_for_true")) {
    //your code for the checkbox value
    checked=true;
}
//the rest of your code use the var checked and not the request.getParameter()
Tomas Narros