JSF Tutorial - JSF JDBC Setup Example








The following code shows how to load data from backend database and display the data with JSF.

Example

The following code is from Customer.java.

package com.java2s.common;

import java.util.Date;

public class Customer{
  
  public long customerID;
  public String name;
  public String address;
  public Date created_date;
  
  public long getCustomerID() {
    return customerID;
  }
  public void setCustomerID(long customerID) {
    this.customerID = customerID;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getAddress() {
    return address;
  }
  public void setAddress(String address) {
    this.address = address;
  }
  public Date getCreated_date() {
    return created_date;
  }
  public void setCreated_date(Date created_date) {
    this.created_date = created_date;
  }
}

The following code is from table-style.css.

.order-table{   
  border-collapse:collapse;
}

.order-table-header{
  text-align:center;
  background:none repeat scroll 0 0 #E5E5E5;
  border-bottom:1px solid #BBBBBB;
  padding:16px;
}

.order-table-odd-row{
  text-align:center;
  background:none repeat scroll 0 0 #FFFFFFF;
  border-top:1px solid #BBBBBB;
}

.order-table-even-row{
  text-align:center;
  background:none repeat scroll 0 0 #F9F9F9;
  border-top:1px solid #BBBBBB;
}

The following code is from CustomerBean.java.

package com.java2s.common;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;


@ManagedBean(name="customer")
@SessionScoped
public class CustomerBean implements Serializable{
  //resource injection
  @Resource(name="jdbc/java2s")
  private DataSource ds;
  //if resource inject is not support, you still can get it manually.
  public CustomerBean(){
    try {
      Context ctx = new InitialContext();
      ds = (DataSource)ctx.lookup("java:comp/env/jdbc/java2s");
    } catch (NamingException e) {
      e.printStackTrace();
    }
  }
  
  //connect to DB and get customer list
  public List<Customer> getCustomerList() throws SQLException{
    if(ds==null)
      throw new SQLException("Can't get data source");
    //get database connection
    Connection con = ds.getConnection();
    
    if(con==null)
      throw new SQLException("Can't get database connection");

//        con.createStatement().executeUpdate("create table customer(customer_id varchar(45),"
  //          +" name varchar(45),"
    //        +"address varchar(45),"+
      //      "created_date date)");

         con.createStatement().executeUpdate("insert into customer(customer_id,"
            +" name ,"
            +"address,"+
            "created_date)values('1','java2s','Main Street',null)");
    
    PreparedStatement ps 
      = con.prepareStatement(
        "select customer_id, name, address, created_date from customer"); 
    ResultSet result =  ps.executeQuery();
    List<Customer> list = new ArrayList<Customer>();
    while(result.next()){
      Customer cust = new Customer();
      cust.setCustomerID(result.getLong("customer_id"));
      cust.setName(result.getString("name"));
      cust.setAddress(result.getString("address"));
      cust.setCreated_date(result.getDate("created_date"));
      list.add(cust);
    }
    return list;
  }
}

The following code is from context.xml.

<Context>
<!--
  <Resource name="jdbc/java2s" 
            auth="Container" 
            type="javax.sql.DataSource"
            maxActive="100" 
            maxIdle="30" 
            maxWait="10000"
            username="sa" 
            password="" 
            driverClassName="com.mysql.jdbc.Driver"
            url="jdbc:mysql://localhost:3306/java2s"/>

-->
  <Resource name="jdbc/java2s" 
            auth="Container" 
            type="javax.sql.DataSource"
            maxActive="100" 
            maxIdle="30" 
            maxWait="10000"
            username="SA" 
            password="" 
            driverClassName="org.hsqldb.jdbc.JDBCDriver"
            url="jdbc:hsqldb:mydatabase"/>

</Context>

The following code is from default.xhtml.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"   
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      >
    <h:head>
      <h:outputStylesheet library="css" name="table-style.css"  />
    </h:head>
 
    <h:body>
     <h:dataTable value="#{customer.getCustomerList()}" var="c"
          styleClass="order-table"
          headerClass="order-table-header"
          rowClasses="order-table-odd-row,order-table-even-row">
         <h:column>
          <f:facet name="header">Customer ID</f:facet>#{c.customerID}
        </h:column>
        <h:column>
          <f:facet name="header">Name</f:facet>#{c.name}
        </h:column> 
       <h:column>
          <f:facet name="header">Address</f:facet>#{c.address}
        </h:column>        
        <h:column>
          <f:facet name="header">Created Date</f:facet>#{c.created_date}
        </h:column>        
      </h:dataTable>     
    </h:body> 
</html>


Download JDBC_Setup.zip





To RUN

Copy the generated WAR file from the target folder to Tomcat deployment folder and run Tomcat-Install-folder/bin/startup.bat.

After Tomcat finish starting, type the following URL in the browser address bar.

http://localhost:8080/simple-webapp/default.xhtml