1
I started learning Java recently and I am facing lot of simple but irritating issues. I spent a lot of time trying to figure out the problem in vain.

I am trying to run a simple registration (with 3 pages) and submit the values into a DB. I am getting `NullPointerException` and not sure how to proceed with debugging any help will be greatly appreciated.

`form1.html`

Form details:

    <!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>
        <form action="./registration" method="get">
                Name:<input type="text" name="name"><br/> 
        Father Name: <input type="text" name="fname"><br/> 
        Mother Name: <input type="text" name="mname"><br/> 
                     <input type="hidden" name="formd" value="1"/>
                     <input type="submit" value="Next>>>">
        </form>
    </body>
    </html>

`form2.html`

    <!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>
    <form action="./registration">
        Contact:<input type="text" name= "contact"><br/>
        Email: <input type= "text" name= "email"><br/>
        Address: <input type ="text" name= "address"><br/>
        <input type="hidden" name= "formd" value="2"/>
        <input type= "submit" value="Next>>>">
    </form>
    </body>
    </html>

`form3.html`

    <!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>
    <form action="./registration">
        Qualification:<input type="text" name= "qualification"><br/>
        Percentage: <input type ="text" name= "percentage"><br/>
        <input type="hidden" name= "formd" value="3"/>
        <input type= "submit" value="Submit!">
    </form>
    </body>
    </html>

**My Servlet**

    package controller;

    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;

    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 AadharRegistration extends HttpServlet {
        private static final long serialVersionUID = 1L;

        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            PrintWriter out = response.getWriter();

            HttpSession httpsession = request.getSession();
            String fno = request.getParameter("formd");

            if (fno.equals("1")) {
                String name = request.getParameter("name");
                String fname = request.getParameter("fname");
                String mname = request.getParameter("mname");

                httpsession.setAttribute("name", name);
                httpsession.setAttribute("fname", fname);
                httpsession.setAttribute("mname", mname);

                response.sendRedirect("./form2.html");
            }

            if (fno.equals("2")) {
                String contact = request.getParameter("contact");
                String email = request.getParameter("email");
                String address = request.getParameter("address");

                httpsession.setAttribute("contact", contact);
                httpsession.setAttribute("email", email);
                httpsession.setAttribute("address", address);

                response.sendRedirect("./form3.html");

            }

            if (fno.equals("3")) {

                String qualification = request.getParameter("qualification");
                String percentage = request.getParameter("percentage");

                String name = (String) httpsession.getAttribute("name");
                String fname = (String) httpsession.getAttribute("fname");
                String mname = (String) httpsession.getAttribute("mname");

                String contact = (String) httpsession.getAttribute("contact");
                String email = (String) httpsession.getAttribute("email");
                String address = (String) httpsession.getAttribute("address");

                try {
                    Class.forName("oracle.jdbc.OracleDriver");
                    Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:p1aor01", "system",
                            "sysdba");

                    PreparedStatement ps = conn.prepareStatement("insert into aadhar values (?,?,?,?,?,?,?,?)");
                    ps.setString(1, name);
                    ps.setString(2, fname);
                    ps.setString(3, mname);
                    ps.setString(4, contact);
                    ps.setString(5, email);
                    ps.setString(6, address);
                    ps.setString(7, qualification);
                    ps.setString(8, percentage);

                    int res = ps.executeUpdate();

                    if (res != 0) {
                        out.println("<font color='green'><h1>Registered Successfully!</h1>");
                    }

                } catch (SQLException e) {
                    out.println("<font color='red'><h1>Registration exception Failed!</h1>");
                    e.printStackTrace();
                } catch (ClassNotFoundException xe) {
                    xe.printStackTrace();
                }
            }
        }

    }

I forgot to add Web.xml. please see below. If i use Dynamic web module version 3.1,i read that we do not need web.xml. Can i still use it? http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> TestAadharRegistration AadharRegistration AadharRegistration controller.AadharRegistration AadharRegistration /registration

**Error:**

    java.lang.NullPointerException
        controller.AadharRegistration.doGet(AadharRegistration.java:26)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
        org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)


    Note The full stack trace of the root cause is available in the server logs.

    From Console in eclipse:
    SEVERE: Servlet.service() for servlet [AadharRegistration] in context with path [/TestAadharRegistration] threw exception
    java.lang.NullPointerException
        at controller.AadharRegistration.doGet(AadharRegistration.java:26)
  • 1
    What is line 26? How is form1.html initially displayed? – Andrew S May 14 '18 at 18:05
  • Can you post the URL you see on address bar after submission, and contents of web.xml where this servlet is registered.. – Vasan May 14 '18 at 18:07
  • Also, the code is for a http get method, but the html is a post. – Andrew S May 14 '18 at 18:08
  • 1
    @AndrewS The default form method is GET. Also, it does enter the `doGet()` method so.. – Vasan May 14 '18 at 18:09
  • if a form method is not specified, it defaults to a GET. – Jonathan Laliberte May 14 '18 at 18:32
  • I cleaned the project and restarted the Tomcat server. url: http://localhost:9999/TestAadharRegistration/ getting the error,HTTP Status 404 – Not Found. Type Status Report Message /TestAadharRegistration/ Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. – aloneonthe_edge May 15 '18 at 01:35
  • @vasan. I have added web.xml by editing initial post – aloneonthe_edge May 15 '18 at 02:02

2 Answers2

0

For some reason this line

 if (fno.equals("1")) {

is throwing the NullPointerException.

Which means your form is not sending the value. i.e. This is null:

String fno = request.getParameter("formd");

Before doing various operations on data, it's important to check if it is null. Otherwise you will get a NullPointerException if it is null. You can check for null like this:

if(fno != null && fno.equals("1")){

In this case, you'll need to find out why fno is null, because it shouldn't be if you have sent the value via the form. This is where browser developer tools can be useful.

If you're in Chrome, right click on your page and click "inspect".. Then click on the network panel. Now make sure you have checked the "Preserve log" checkbox at the top and then submit the form again. You will see a bunch of things happening, click on the one with your URL on it and then look at the headers. Scroll down and there will be a section called "Query String Parameters", here you can see what your form is sending to your servlet. If "formd" is not there, then that is why you are getting a NullPointerException.

Jonathan Laliberte
  • 2,672
  • 4
  • 19
  • 44
  • Hello Jon, Yes i did sysout and i do see the value is being passed as "null" not sure what is going wrong. its simple html. I did follow your instructions and i do not see "Query String Parameters". I only see 3 Sub headers. 1 General. 2.Response headers and 3.Request headers – aloneonthe_edge May 15 '18 at 01:45
  • It might be different for you. Have a look at this, it will explain it better. When you figure it out let us know what is being passed... https://www.google.co.uk/url?sa=t&source=web&rct=j&url=https://stackoverflow.com/questions/15603561/how-can-i-debug-a-http-post-in-chrome&ved=2ahUKEwiD4bKOzYbbAhUlDMAKHbxSBacQFjAAegQICRAB&usg=AOvVaw3RxkHFpQtPeFA_6A475eWb – Jonathan Laliberte May 15 '18 at 01:51
  • Hello Jon,i followed the steps mentioned in the article above but still could find anything that states "Query String Parameters" Request URL: http://localhost:9999/TestAadharRegistration/ Request Method: GET Status Code: 404 Remote Address: [::1]:9999 Referrer Policy: no-referrer-when-downgrade Content-Language: en Content-Length: 1101 Content-Type: text/html;charset=utf-8 Date: Tue, 15 May 2018 04:09:02 GMT – aloneonthe_edge May 15 '18 at 04:17
  • Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Cache-Control: max-age=0 Connection: keep-alive Host: localhost:9999 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.170 Mobile Safari/537.36 This is what all i see – aloneonthe_edge May 15 '18 at 04:18
  • Sorry, it's actually under a section called "Form Data". You should see 4 sections... General, Response Headers, Request Headers and Form Data. – Jonathan Laliberte May 15 '18 at 15:21
  • I do not see anything called "Form Data" I just see only 3 sections General,Response Headers,and Request Headers. – aloneonthe_edge May 15 '18 at 18:01
  • well then your form is not actually sending anything, which would explain why it is null. Do a sysout on your other parameters, double check to see if they are null also – Jonathan Laliberte May 15 '18 at 18:02
  • Hi Jon, That is what i am failing to understand. its a simple form and not sure what am i missing – aloneonthe_edge May 16 '18 at 01:59
  • 1
    Hi Jon, I found the answer for the problem.I mentioned it few days back in the same thread but did not realize that i did not "Thank you" for your help. Thanks buddy..very much appreciated – aloneonthe_edge May 22 '18 at 03:23
  • no problem, feel free to give the answer an upvote/tick if it helped solve your problem. :) – Jonathan Laliberte May 22 '18 at 03:41
0

after spending hell lot of time,i realized the mistake. In web.xml, i did not have any welcome-file listed and when i ran the project, it stopped till application project and form data was not submmitted. hence the value was "null". Thanks for helping with different options.