0

I have been working on simple banking project and I am on the initial stage. What I want is to save the customer information in database through register.html and RegisterServlet.java pages. But unfortunately, it stopped working with an NullPointerException. I have been trying to resolve this issue from last 3 days but no solution. I am including my GitHub link too GitHub Jdbc Banking Project Link and in jar file I have included ojdbc6 only. My code is breaking in try block line (ps = con.prepareStatement("insert into customers(name,email,mobile,city,dob) values (?,?,?,?,?)");) I need some serious help.

My pages
1. login.html
2. register.html
3. RegisterServlet.java
4. DBConnectionManager.java
5. web.xml

register.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<h3 align="center">Customer Registration Page</h3>
<form action="RegisterServletPath" method="post">
<table align="center">
    <tr>
        <td>Customer Name</td>
        <td><input type="text" name="name"></td>
    </tr>
    
    <tr>
        <td>Email</td>
        <td><input type="text" name="email"></td>
    </tr>
    
    <tr>
        <td>Mobile</td>
        <td><input type="text" name="mobile"></td>
    </tr>
    
    <tr>
        <td>City</td>
        <td><input type="text" name="city"></td>
    </tr>
        
    <tr>
        <td>DOB</td>
        <td><input type="date" name="dob"></td>
    </tr>
    
    <tr>
        <td></td>
        <td><input type="submit" value="Register"></td>
    </tr>
    
</table>
</form>

</body>
</html>

RegisterServlet.java

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

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class RegisterServlet
 */
//@WebServlet("/RegisterServletPath")
@WebServlet(name="RegisterServlet", urlPatterns={"/RegisterServletPath"})
public class RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
        System.out.println("Inide doGet method");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        System.out.println("Inside doPost method");
        PrintWriter out = response.getWriter();
        out.print("<html><h3>It is coming from RegisterServlet.java</h3></html>");
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String mobile = request.getParameter("mobile");
        String city = request.getParameter("city");
        String dob = request.getParameter("dob");
        
        /*write the logic for input validation*/
        String errorMsg = null;
        if(name == null || name.equals("")) {
            errorMsg = "Name can't be empty";
        }
        if(email == null || email.equals("")) {
            errorMsg = "Email can't be empty";
        }
        if(mobile == null || mobile.equals("")) {
            errorMsg = "Mobile number can't be empty";
        }
        if(city == null || city.equals("")) {
            errorMsg = "City name can't be empty";
        }
        if(dob == null || dob.equals("")) {
            errorMsg = "Date of birth can't be empty";
        }
        
        System.out.println("Line 64");
        
        //when the text field is not null, this code statement won't run
        if(errorMsg != null) {
            System.out.println("Line 67");
            RequestDispatcher rd = getServletContext().getRequestDispatcher("/register.html");
            PrintWriter out1 = response.getWriter();
            out1.println("<font color=red>" +errorMsg+"</font>");
            rd.include(request, response);
        }
        
    //  System.out.println("Line 73");
        else {
            System.out.println("Line 73");
            Connection con = (Connection)getServletContext().getAttribute("DBConnection");
            PreparedStatement ps = null;
            System.out.println("Line 79");
            
            
            try{
                System.out.println("Line 81");
                ps = con.prepareStatement("insert into customers(name,email,mobile,city,dob) values (?,?,?,?,?)");
                System.out.println("Line 82");
                ps.setString(1, name);
                ps.setString(2, email);
                ps.setString(3, mobile);
                ps.setString(4, city);
                ps.setString(5, dob);
                System.out.println("Line 87");  
                ps.execute();
                
                //forward to login page to login
                RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
                PrintWriter out1 = response.getWriter();
                out1.println("<font color=green>Registration Successful, please login.</font>");
                rd.include(request, response);
                
            }
            catch(SQLException e) {
                e.printStackTrace();
                //logger.error("Database connection problem");
                throw new ServletException("DB Connection Problem");
            }
            finally {
                try {
                    ps.close();
                }
                catch(SQLException e) {
                    System.out.println("Inside second catch block");
                    //logger.error("SQLException is closing PreparedStatement");
                }
            }
        }
        
        
        //doGet(request, response);
    }
    

}

DBConnectionManager.java

package com.banking.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/*
 * DBConnectionManager.java is a utility class for Oracle11g database connection and it has a method that
 * returns connection object. We will use this class for database connection and then set the connection
 * to servlet context attribute(web.xml) that other servlets can use.
 * */

public class DBConnectionManager {
    private Connection connection;
    
        public DBConnectionManager(String dbURL, String username, String password) throws 
        ClassNotFoundException, SQLException {
            
                Class.forName("oracle.jdbc.driver.OracleDriver");
                this.connection = DriverManager.getConnection(dbURL,username,password);
        }
        public Connection getConnection() {
            return this.connection;
        }
}

web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
      <display-name>JDBC Banking Project</display-name>
      <welcome-file-list>
        <welcome-file>register.html</welcome-file>
      </welcome-file-list>
      
      <context-param>
        <param-name>username</param-name>
        <param-value>system</param-value>
      </context-param>
      <context-param>
        <param-name>password</param-name>
        <param-value>123456</param-value>
      </context-param>
      <context-param>
        <param-name>dbURL</param-name>
        <param-value>jdbc:oracle:thin:@localhost:1521:xe</param-value>
      </context-param>
    </web-app>

error console

May 03, 2017 1:02:28 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Hello World' did not find a matching property.
May 03, 2017 1:02:28 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:JDBC Banking Project' did not find a matching property.
May 03, 2017 1:02:28 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version:        Apache Tomcat/7.0.69
May 03, 2017 1:02:28 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built:          Apr 11 2016 07:57:09 UTC
May 03, 2017 1:02:28 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number:         7.0.69.0
May 03, 2017 1:02:28 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name:               Windows 8.1
May 03, 2017 1:02:28 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version:            6.3
May 03, 2017 1:02:28 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture:          amd64
May 03, 2017 1:02:28 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home:             C:\Program Files\Java\jre7
May 03, 2017 1:02:28 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version:           1.7.0_79-b15
May 03, 2017 1:02:28 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor:            Oracle Corporation
May 03, 2017 1:02:28 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE:         D:\Eclipse Workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
May 03, 2017 1:02:28 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME:         C:\Program Files\Apache Software Foundation\Tomcat 7.0
May 03, 2017 1:02:28 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=D:\Eclipse Workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
May 03, 2017 1:02:28 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=C:\Program Files\Apache Software Foundation\Tomcat 7.0
May 03, 2017 1:02:28 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=D:\Eclipse Workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
May 03, 2017 1:02:28 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=C:\Program Files\Apache Software Foundation\Tomcat 7.0\endorsed
May 03, 2017 1:02:28 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1252
May 03, 2017 1:02:28 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre7\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;D:\app\Shital\product\11.2.0\dbhome_1\bin;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x86;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x64;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files (x86)\QuickTime Alternative\QTSystem;C:\Program Files\Java\jdk1.7.0_79\bin;C:\Program Files\Java\jdk1.7.0_79\jre\lib;.
May 03, 2017 1:02:29 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
May 03, 2017 1:02:29 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
May 03, 2017 1:02:29 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 924 ms
May 03, 2017 1:02:29 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
May 03, 2017 1:02:29 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.69
May 03, 2017 1:02:29 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
May 03, 2017 1:02:29 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
May 03, 2017 1:02:29 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 907 ms
Inside doPost method
Line 64
Line 67
Inside doPost method
Line 64
Line 73
Line 79
Line 81
May 03, 2017 1:03:03 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [RegisterServlet] in context with path [/JDBC_Banking_Project] threw exception
java.lang.NullPointerException at RegisterServlet.doPost(RegisterServlet.java:110)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:436)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Lalit Kumar
  • 11
  • 1
  • 1
  • 4

1 Answers1

0

I can't see anywhere in your project you are setting connection in Servlet context not sure if you have posted complete source code.

Connection con = (Connection)getServletContext().getAttribute("DBConnection");

below line throwing NullPointerException

ps = con.prepareStatement("insert into customers(name,email,mobile,city,dob) values (?,?,?,?,?)");

Which cannot be caught in catch clause of SQLException. in finally block when it tries to close the connection. NullPointerException is thrown.

khurram
  • 31
  • 2
  • Hey, I am referring this blog post [http://www.journaldev.com/1997/servlet-jdbc-database-connection-example] but not creating all files. I just wanted to do first basic steps. Will you please look into above link and help me with what I am missing. I have provided all my source code, kept my login.html blank. – Lalit Kumar May 03 '17 at 09:37
  • if i see code on git then AppContextListener is missing from your code. – khurram May 03 '17 at 10:01
  • Hi, so I have added AppcontextListener.java in my project but still, it is giving the same output. Will you please check out my GitHub link again. It will be very helpful for me. – Lalit Kumar May 04 '17 at 06:11