How to Connect to PostgreSQL Database Server from a Java Web Application using Primefaces Framework

Posted on

Introduction

This article will focus on how to connect to a PostgreSQL database server. The connection itself is from a Java web application running using a Primefaces framework. In this article, the project structure and environment is using the setting and configuration from several previous articles. First of all, it is an article with the title of ‘How to Create maven-based Web Application in NetBeans IDE’. Actually, that article is available in this link. The second one, it is an article in this link. That second one, it has the title of ‘How to Add JSF Library to a maven-based Web Application in NetBeans IDE’. The next one, it is the last article exist in this link. As a reference, that last article has the title of ‘How to Add Primefaces Library to a maven-based Java Web Application in NetBeans IDE’. In all of those articles, each of them are informing different subject. In the first one, it is informing about how to create a maven-based Java web application. In the second article, it informs about how to add a JSF library to the Java web application project. Respectively, in the last article, it describes about how to add Primefaces framework functionality on the project.

Connect to PostgreSQL Database Server from Java Web Application using Primefaces Framework

First of all, there are several steps for connecting to a database server. In this context, it is connecting to PostgreSQL database server. Specifically, those steps will be available in two parts. As an easy way to understand it better. The first part is focusing on the configuration and preparation. On the other hand, the second one is for the execution part. So, the steps to accomplish that purpose exist below :

Prepare and Configure the necessary File

In summary, it is possible to connect to a database. Hence, it requires several files to be available. First of all, there is a file for the UI or the User Interface for the user in the form of JSF file. Moreover, there is also a file for processing the request from the JSF file. It acts as the backing bean of it in the form of Java file. Furthermore, there is a last file which is a Java file. In this case, that Java file is specifically focus for database connection process. Those files will be available in the following steps :

  1. At first, the important step is to register the right driver definition in the ‘pom.xml’ file of the project. Just search the driver package name for further definition in the maven repository. At this time, the maven repository exist in this link. Use the name ‘postgresql’ in the following database driver package name. Therefore, it will be available for further definition in the ‘pom.xml’ file as exist below :

    <!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
    <dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.3.4</version>
    </dependency>
    

    Then, add the above part in the ‘dependencies’ section in the ‘pom.xml’ file as follows :

    <dependencies> 
    ....
       <!-- https://mvnrepository.com/artifact/org.postgresql/postgresql --> 
       <dependency> 
            <groupId>org.postgresql</groupId> 
            <artifactId>postgresql</artifactId> 
            <version>42.3.4</version> 
       </dependency>
    ....
    </dependencies>
    
  2. The second step, create one Java file to get the Connection object. In this context, that connection object is useful for connecting to the database server. As an example, it is Java file with the name of ‘DBConnection.java’. Inside of it, there is a content for creating Connection object :

    /*
    * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
    * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
    */
    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 Mark 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("Database Connection Failure");
                  Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
                  ex.printStackTrace();
                  return null;
              }          
         }
    }
  3. In the next step, create a JSF file. It acts as a triggering process for connecting to the database. There is a button element for form submission in the JSF file. In this context, it is a JSF file with the name of ‘db-connection-test.xhtml’. Below is the content of that file :

    <?xml version="1.0" encoding="UTF-8"?>
    <!--
    Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
    Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/XHtml.xhtml to edit this template
    -->
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml"
          xmlns:h="http://java.sun.com/jsf/html"
          xmlns:f="http://java.sun.com/jsf/core"
          xmlns:p="http://primefaces.org/ui">
          <h:head>
               <title>Database Connection</title>
               <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
          </h:head>
          <body>
               <h:form>
                   <p:outputPanel>
                        <p:outputLabel id="connectionStatus" value="#{dbConnectionTestView.status}"></p:outputLabel>
                   </p:outputPanel>
                   <p:commandButton type="submit" value="Alert" onclick="alert('Prime')" actionListener="#{dbConnectionTestView.submit()}" update="@form"/>
               </h:form>
          </body>
    </html>
  4. So, just continue on to the next step. Create a Java file which acts as the backing bean of the previous JSF file. It will process the request for connecting to the database as follows :

    /*
    * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
    * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
    */
    package com.mycompany.web.view;
    
    import com.mycompany.web.db.DBConnection;
    import java.io.Serializable;
    import java.sql.Connection;
    import javax.faces.view.ViewScoped;
    import javax.inject.Named;
    
    /**
    *
    * @author Mark Spectre
    */
    @Named(value = "dbConnectionTestView")
    @ViewScoped
    public class DBConnectionTestView implements Serializable {
         private Connection connection;
         String DEFAULT_DB_CONNECTION = "Not Connected";
         String DB_CONNECT_SUCCESS = "Database Connection is a success";
         String DB_CONNECT_FAILED = "Database Connection is failed";
         private String status = DEFAULT_DB_CONNECTION;
    
         static void init(){
             String url = "jdbc:postgresql://localhost:5432/employee";
             String username = "postgres";
             String password = "password";
         }
    
         public String getStatus() {
             return status;
         }
    
         public void setStatus(String status) {
             this.status = status;
         }
    
         public void submit(){
             connection = DBConnection.getConnection();
             if(connection != null)
                  this.setStatus(DB_CONNECT_SUCCESS);
             else
                  this.setStatus(DB_CONNECT_FAILED);
             System.out.println("Submit from JSF file");
         }
    }

Run, Execute and Test for Database Connection

This part is the continuation of the previous part. It is focusing on the testing of the database connection. For testing the database connection, the following are the steps to perform it  :

  1. First of all, build, compile and run the Java web application and access the ‘db-connection-test.xhtml’. A page for displaying ‘db-connection-test.xhtml’ will appear as follows :

    How to Connect to PostgreSQL Database Server from a Java Web Application using Primefaces Framework
    How to Connect to PostgreSQL Database Server from a Java Web Application using Primefaces Framework
  2. Finally, click the submit button with the alert label. Suddenly, there will be an alert in the form of window pop-up. Continue on, click the OK button to proceed. So, the process will continue on by connecting to the database. As a result, it will update the form. Therefore, it will update the form by changing the outputLabel component from ‘Not Connected’ to another status. Next after, if the database connection is a success, the outputLabel value will change into ‘Database Connection is a success’ or ‘Database Connection is failed’. In other words, it change depends on the connection attempt to the database. As an example, the following image will show the successful attempt of the database connection process :

    How to Connect to PostgreSQL Database Server from a Java Web Application using Primefaces Framework
    How to Connect to PostgreSQL Database Server from a Java Web Application using Primefaces Framework
  3. Next step, click the OK button as in the alert popup window above. Soon, it will direct to the following page exist as in the image below :

    How to Connect to PostgreSQL Database Server from a Java Web Application using Primefaces Framework
    How to Connect to PostgreSQL Database Server from a Java Web Application using Primefaces Framework

    In the end, the outputLabel component’s value will change. Basically, the reason is because the database connection process is a success. In other words, the value of the outputLabel will switch from ‘Not Connected’ to ‘Database Connection is a success’.

One thought on “How to Connect to PostgreSQL Database Server from a Java Web Application using Primefaces Framework

Leave a Reply