How to Solve Error Message Caused by: java.lang.NullPointerException: Cannot invoke “java.sql.Connection.prepareStatement(String)” because “this.connection” is null when executing Java Web Application using Primefaces Framework solve by adding Database Driver

Posted on

Introduction

This article is pointing out the situation where an error message appear. The error message exist as part of the title of this article. Morever, in order to describe the condition better, just look at the previous articles. Those articles are becoming the reference source for this article. Those articles are the one with the title of ‘How to Create maven-based Web Application in NetBeans IDE’ which exist in this link. Another one is an article available in this link with the title of ‘How to Add JSF Library to a maven-based Web Application in NetBeans IDE’. And the last one is the article in this link with the title of ‘How to Add Primefaces Library to a maven-based Java Web Application in NetBeans IDE’.

As in the previous statement, there is an error message exist. That error message is “Caused by: java.lang.NullPointerException: Cannot invoke “java.sql.Connection.prepareStatement(String)” because “this.connection” is null” as part of the title. As in the error message point out, the cause for the error message appearance is because of the connection object or connection variable is null. Before getting in to the solution part, the following is the actual script for database connection. The first one is the file with the name of DBConnection.java which consists of the database configuration connection. It will return a Connection object or variable for further database connection process. The file exist with the following content :

package com.mycompany.web.db;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Marc Spectre
*/
public class DBConnection {
    private static String url, user, password;
    static void init() {
        url = "jdbc:postgresql://localhost:5432/employee"; 
        user = "postgres"; 
        password = "password"; 
    }
    public static Connection getConnection() {
       init();
       try {
           return DriverManager.getConnection(url, user, password);
       } catch (SQLException ex) {
           System.out.println("Error Connection");
           Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
           ex.printStackTrace();
           return null;
       }
    }
}

The other important file which is a Java file as a backing bean of the JSF file is the one with the name of ‘BasicInputTextDBView.java’. The content exist as follows :

package com.mycompany.web.view;
import com.mycompany.web.bean.UserBean;
import com.mycompany.web.db.DBConnection;
import com.mycompany.web.model.User;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
/**
*
* @author Mark Spectre
*/
@Named(value = "basicInputTextDBView")
@ViewScoped
public class BasicInputTextDBView implements Serializable {
    private Connection connection;
    private Statement statement;
    private ResultSet resultSet;
    private final String TABLE_NAME = "employee";
    private User user;
    private List<User> userList;
    private String name;
    public BasicInputTextDBView() {
        connection = DBConnection.getConnection();
        System.out.println("Connection : "+connection);
        user = new User();
        userList = user.getUserList();
    }
    public String getName() {
       return name;
    }
    public void setName(String name) {
       this.name = name;
    }
    public void submit() {
       try {
             String query = "INSERT INTO " + TABLE_NAME
                            + "(nama) "
                            + " values(?)";
             System.out.println(query);
             System.out.println("Name : "+name);
             connection = DBConnection.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(query);
             preparedStatement.execute();
             preparedStatement.close();
             preparedStatement.setString(1, name); //getName());
             User user = new User();
             user.setUsername(name);
             userList.add(user);
       } catch (SQLException ex) {
             Logger.getLogger(BasicInputTextDBView.class.getName()).log(Level.SEVERE, null, ex);
       }
    }
}

The scenario in the Java web application begin with the submit process from the JSF form exist in a file with the name of ‘basic-text-input-db.xhtml’. Moving on, below is the content of the ‘basic-text-input-db.xhtml’ :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:p="http://primefaces.org/ui">
      <head>
            <title>TODO supply a title</title>
            <meta name="viewport" content="width-device-width, initial-scale=1.0"> 
      </head>
      <body>
            <div>TODO content</div>
            <div class="card">
                 <h:form>
                 <h5>Form User with only Basic InputText</h5>
                 <h5>Hello, <p:outputLabel for="username" value="#{basicInputTextDBView.username}"></p:outputLabel></h5>
                 <p:inputText id="username" value="#{basicInputTextDBView.username}"/>
                 <p:commandButton actionListener="#{basicInputTextDBView.submit()}" value="Submit" />
                 </h:form> 
            </div>
            <div class="card">
                 <p:panel header="User List">
                    <p:dataTable var="user" value="#{userBean.userList}">
                        <p:column>
                           <f:facet name="header">
                              <h:outputText value="Username" />  
                           </f:facet>
                           <h:outputText value="#{user.username}" />  
                        </p:column>
                    </p:dataTable>
                 </p>
            </div>
      </body>
</html>

Submitting the form will redirect the process to the method available as the value of the ‘actionListener’ attribute. A method with the name of ‘submit’ exist in the Java Bean with the annotation name as ‘basicInputTextDBView’. Unfortunately, in the attempt for getting the connection object or value, it is getting the null value. After searching the location of the null value in the above script, it exist in the the ‘submit’ method as in the following line :

connection = DBConnection.getConnection();

Solving the Error Message

After getting on the information about the Java file above for defining the connection object which is getting a null value, there are several steps for solving the problem. Actually, the most general trigger for causing the error is the absense of the database driver. In other words, there is no database driver definition in the ‘pom.xml’ file describing the project. So, the first step to solve is just take a look at the Database Driver available in the ‘pom.xml’ file available. If there are no database driver definition at all, just define the right one.

Checking the pom.xml of the Java Web Application Project

In this part, just check the ‘pom.xml’ file before adding a database driver definition. The actual content of the ‘pom.xml’ file available in the following description :

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mycompany.web</groupId>
    <artifactId>app</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>app-1.0-SNAPSHOT</name>
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <failOnMissingWebXml>false</failOnMissingWebXml>
        <jakartaee>8.0</jakartaee>
    </properties>
    <dependencies>
        <dependency>
             <groupId>javax</groupId>
             <artifactId>javaee-api</artifactId>
             <version>${jakartaee}</version>
             <scope>provided</scope>
        </dependency>
        <dependency>
             <groupId>org.primefaces</groupId>
             <artifactId>primefaces</artifactId>
             <version>11.0.0</version>
        </dependency>
     </dependencies>
     <build>
         <plugins>
              <plugin>
                   <groupId>org.apache.maven.plugins</groupId>
                   <artifactId>maven-compiler-plugin</artifactId>
                   <version>3.1</version>
                   <configuration>
                       <source>1.8</source>
                       <target>1.8</target>
                       <compilerArguments>
                           <endorseddirs>${endorsed.dir}</endorseddirs>
                       </compilerArguments>
                   </configuration>
              </plugin>
              <plugin>
                   <groupId>org.apache.maven.plugins</groupId>
                   <artifactId>maven-war-plugin</artifactId>
                   <version>3.3.2</version>
                   <configuration>
                        <failOnMissingWebXml>false</failOnMissingWebXml>
                   </configuration>
              </plugin>
              <plugin>
                   <groupId>org.apache.maven.plugins</groupId>
                   <artifactId>maven-dependency-plugin</artifactId>
                   <version>3.3.0</version>
                   <executions>
                       <execution> 
                           <phase>validate</phase>
                           <goals>
                               <goal>copy</goal>
                           </goals>
                           <configuration>
                               <outputDirectory>${endorsed.dir}</outputDirectory>
                               <silent>true</silent>
                               <artifactItems>
                                    <artifactItem>
                                         <groupId>javax</groupId>
                                         <artifactId>javaee-api</artifactId>
                                         <version>${jakartaee}</version>
                                         <type>jar</type>
                                    </artifactItem>
                               </artifactItems>
                           </configuration>
                      </execution>
                 </executions>
             </plugin>
          </plugins>
    </build>
</project>

Adding the Database Driver Definition in pom.xml of the Java Web Application Project

Unfortunately, as it exist above, there are no database driver definition available in the ‘pom.xml’ file. So, that is the reason for why it cause the error message to appear. As an example in this article, the Java web application is using PostgreSQL database server as its database. Just search the suitable PostgreSQL database driver in the maven repository. According to the result search, there will be the right one available in the maven repository as follow :

    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.3.4</version>

Using the database driver definition above, just add the database driver definition to the ‘pom.xml’ file as follows :

    <dependencies>
        <dependency>
             <groupId>javax</groupId>
             <artifactId>javaee-api</artifactId>
             <version>${jakartaee}</version>
             <scope>provided</scope>
        </dependency>
        <dependency>
             <groupId>org.primefaces</groupId>
             <artifactId>primefaces</artifactId>
             <version>11.0.0</version>
        </dependency>
        <dependency>
             <groupId>org.postgresql</groupId>
             <artifactId>postgresql</artifactId>
             <version>42.3.4</version>
        </dependency>
     </dependencies>

Finally, just build, compile and run the Java web application once more. In the end, if there are no further error appear, it will run normally using the available PostgreSQL database connection.

One thought on “How to Solve Error Message Caused by: java.lang.NullPointerException: Cannot invoke “java.sql.Connection.prepareStatement(String)” because “this.connection” is null when executing Java Web Application using Primefaces Framework solve by adding Database Driver

Leave a Reply