Using Database in Jave Server Faces

This is a very simple example approach to create a data table in Java Server Faces.
Java Server Faces is a new Web Application Framework for developing Web application using Java Technology.

In this article, I will show you how to develop a detatable using JSF(Java Server Faces).
The <h:datatable> tag of jsf provides this facility. This facility reduces lots of development time as well as size of code of jsp page and makes the code very clear in terms of readability.

We will show the functionality using Example Application step by step.
The Example Flow Diagram is as given in figure 1



Step 1 : Create The Wrapper Class as Data Transfer Object.

This wrapper class is nothing but a simple Java Bean Class with setter and getter method for that class. Let assume that we want our friends information in the table so that  we can see all or some of them using paging (explained later).This class represents a row in the datatable we are going to create.

Let say Person is the class which has attribute like

1 : Id
2 : First Name
3 : Last Name
4 : Name Of City
5 : Contact Number

The Class definition of “Person.java” is as follow.

...........................................................................................................................................................................
/ * 
* Class : Person.java
* /
package common;

public class Person{
private Long lngID;
private String strFirstName;
private String strLastName;
private String strCity;
private String strContactNo;

public Person(){

}

public void setLngID( Long lngID ){
this.lngID = lngID;
}

public Long getLngID(){
return lngID;
}

public void setStrFirstName( String strFirstName ){
this.strFirstName = strFirstName;
}

public String getStrFirstName(){
return strFirstName;
}

public void setStrLastName( String strLastName ){
this.strLastName = strLastName;
}

public String getStrLastName(){
return strLastName;
}

public void setStrCity( String strCity ){
this.strCity = strCity;
}

public String getStrCity(){
return strCity;
}

public void setStrContactNo( String strContactNo ){
this.strContactNo = strContactNo;
}

public String getStrContactNo(){
return strContactNo;
}
}//End of Person.java class definition

Step 2 : Create Data Access Object and retrive data in ArrayList

Here is a PersonDAO.java class which encapsulates Data Access Logic and return the java.util.ArrayList which contains the objects of PersonDTO (which represents a row in “friends” table in Oracle).

...........................................................................................................................................................................
/ *
* PersonDAO.java of getting Connection and retrieving data
* /
package model;

import common.Person;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.ArrayList;

public class PersonDAO{

private String ORACLE_USER_NAME = "scott";
private String ORACLE_PASSWORD = "tiger";

public PersonDAO(){}

public Connection getConnection(){
return this.getOracleConnection();
}

public Connection getOracleConnection(){
Connection con = null;
try{
con = null;
Class.forName( "oracle.jdbc.driver.OracleDriver" );
con = 
DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:orcl", 
ORACLE_USER_NAME, ORACLE_PASSWORD );
System.out.println( "Got Connection" );
} catch( ClassNotFoundException e ){
e.printStackTrace();
} catch( SQLException se ){
se.printStackTrace();
}
return con;
}
public List getFriendsList(){
List friendList = new ArrayList();
Connection con = getConnection();
Statement stmt = null;
ResultSet rs = null;
String query = "SELECT * FROM FRIENDS";
try{
stmt = con.createStatement();
rs = stmt.executeQuery(query);
while(rs.next()){
Person person = new Person();
if(rs.getString(1)!=null)person.setLngID(new Long(rs.getString(1))); 
if(rs.getString(2)!=null)person.setStrFirstName(rs.getString(2));
if(rs.getString(3)!=null)person.setStrLastName(rs.getString(3));
if(rs.getString(4)!=null)person.setStrCity(rs.getString(4));
if(rs.getString(5)!=null)person.setStrContactNo(rs.getString(5));
friendList.add(person);
}
} catch( SQLException e ){
System.out.println( e.getMessage() );
closeResources( con, stmt, rs );
}
return friendList;
}

public void closeResources( Connection con, Statement stmt, ResultSet rs ){
try{
rs.close();
stmt.close();
con.close();
} catch( SQLException e ){
System.out.println( e.getMessage() );
}
}
public static void main(String[] args){
PersonDAO pdao = new PersonDAO();
pdao.getFriendsList();
}
}//end of PersonDAO.java class

In the above class in getFriendsList() method we have create instances of PersonDTO and populated data from resultset into the instance of that DTO and finally we added all the instances into ArrayList which we will use in hacking bean for representing in friends.jsp page.


Step 3 : Create And Use Backing Bean To Store and Retrive Data

There are various types of data retrieval facilities available in Java. You can use plain JDBC statements to retrieve data, you can use entity beans if your data are distributed or you can use popular ORM technology like HIBERNATE for the same.
When you retrieve data , you can put your data into the instance of DTO and you can put all DTOs in one Collection objects like Array List.

Here is the backing bean which populated data using java.uitl.ArrayList instance.


...........................................................................................................................................................................
package view.backing;

import java.util.ArrayList;
import javax.faces.context.FacesContext;
import model.PersonDAO;

public class PersonBkb{

private ArrayList friendsList;

public PersonBkb(){

}

public void getFriends(){
PersonDAO personDAO = new PersonDAO();
friendsList = (ArrayList)personDAO.getFriendsList();
System.out.println(friendsList.size());
}

public void setFriendsList( ArrayList friendsList ){
this.friendsList = friendsList;
}

public ArrayList getFriendsList(){
if(FacesContext.getCurrentInstance().getRenderResponse()) {
getFriends();
}
return friendsList;
}
}

Here from getFriendsList() we have called getFriends() which stored data in ArrayList object. 

But before we use this backing bean we have to put <managed-bean> entry into faces-config.xml file and put the scope as “session” as follow.

..........................................................................................................................................................................
<managed-bean>
<managed-bean-name>PersonBkb</managed-bean-name>
<managed-bean-class>view.backing.PersonBkb</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>

Step 4 : Create jsp(OR jsf page) To display Data in a Tabular Manner

Now we will create a jsp page for displaying data as follow.

..........................................................................................................................................................................
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page contentType="text/html;charset=windows-1252"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<f:view>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=windows-1252"/>
<title>friends</title>
<style type="text/css">
</style>
</head>
<body><h:form>
<h:dataTable value="#{PersonBkb.friendsList}" var="friends" border="2" bgcolor="Silver">
<h:column>
<f:facet name="header">
<h:outputText value="frID"/>
</f:facet>
<h:outputText value="#{friends.lngID}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="First Name"/>
</f:facet>
<h:outputText value="#{friends.strFirstName}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Last Name"/>
</f:facet>
<h:outputText value="#{friends.strLastName}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Location"/>
</f:facet>
<h:outputText value="#{friends.strCity}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Value"/>
</f:facet>
<h:outputText value="#{friends.strContactNo}"/>
</h:column>
</h:dataTable>
</h:form></body>
</html>
</f:view>

See the code in blue color in the above source-code. We have <h:datatable> tag with some attributes. 

value="#{PersonBkb.friendsList}":--

In this line PersonBkb is the name of bean as defined in the faces-config.xml and friendList is the java.util.ArrayList Object which is defined in PersonBkb.java class which contains DTO objects.

var="friends" :--

In this line var is a short name for value attribute’s value. Now we can use this “friends” to represent the “PersonBkb.friendsList”. 

<h:column>
<f:facet name="header">
<h:outputText value="frID"/>
</f:facet>
<h:outputText value="#{friends.lngID}"/>
</h:column>


In the above code snippet <h:column> represents a property in the PersonDTO object.
And <outputText> tab is used to actual data resided in the friends table.

When we run the above JSP code output will look like this

That’s is we see how with minimal code in jsp we have seen the datatable.(imagine and try with jsp scriptlet and try to display above table and check which readability is better.

Paging Operation :- Paging is very important when working with datatable , because if we have thousands of record then we can’s display each and every record insimple page , rather we can put (say 10 and 15) rows in page and using “First” “ Last” “Previous” “Next”
For this you need to bind datatable in the javax.faces.component.html.HtmlDataTable variable in backing bean by putting in

  <h:datatable> binding variable like this.
<h:dataTable value="#{PersonBkb.friendsList}"
var="friends"
border="2"
bgcolor="Silver"
binding=”#{PersonBkb.friendsDatatable} >. 

Now you can write your methods on each button using this variable.

Now add the following cod in your backing bean.(PersonBkb.java)

..........................................................................................................................................................................
public void first(){
friendsDatatable.setFirst(0); 


public void previous(){
int first = friendsDatatable.getFirst();
int noOfRows = friendsDatatable.getRows();
friendsDatatable.setFirst(first - noOfRows); 
}

public void next(){
int first = friendsDatatable.getFirst();
int noOfRows = friendsDatatable.getRows();
friendsDatatable.setFirst(first + noOfRows); 
}

public void last(){
int rowCount = friendsDatatable.getRowCount();
int noOfRows = friendsDatatable.getRows();
int first = 0;
if((rowCount % noOfRows)==0) 
first = rowCount - (rowCount % noOfRows);
else
first = rowCount - noOfRows; 
friendsDatatable.setFirst(first); 
}

Now call this method by putting commandbutton and action in your jsp(friends.jsp) page.

..........................................................................................................................................................................
<f:facet name="footer">
<h:panelGroup>
<h:commandButton value="First"
action="#{PersonBkb.first}"
disabled="#{PersonBkb.friendsDatatable.first == 0}"/>
<h:commandButton value="Previous"
action="#{PersonBkb.previous}"
disabled="#{PersonBkb.friendsDatatable.first == 0}"/>
<h:commandButton value="Next"
action="#{PersonBkb.next}"
disabled="#{PersonBkb.friendsDatatable.first + 
PersonBkb.friendsDatatable.rows >= PersonBkb.friendsDatatable.rowCount}"/>
<h:commandButton value="Last"
action="#{PersonBkb.last}"
disabled="#{PersonBkb.friendsDatatable.first + PersonBkb.friendsDatatable.rows >= PersonBkb.friendsDatatable.rowCount}"/>
</h:panelGroup>
</f:facet>

The final output will look like this



Multiselect operations :- 
You can do many operations on <h:datatable> multiselection of rows to do bulk operation like delete multiple rows of using common operation on a group of rows.
You can also alternate the color of rows to show a good look and feel but here I have just tried to show a basic datatable example using JSF.

You can also sort the column using little bit of work. If you want code you can contact me
on preet_mistry@yahoo.com

Rich Datatable Using Adf faces:-

Now I will show you how you can easily do all of the above stuff and adding some more bulk operation using ADF FACES.
loYou just put the following code on a new jsf “say adfFacesdatatable” and run it.


..........................................................................................................................................................................
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page contentType="text/html;charset=windows-1252"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="http://xmlns.oracle.com/adf/faces" prefix="af"%>
<%@ taglib uri="http://xmlns.oracle.com/adf/faces/html" prefix="afh"%>
<f:view>
<afh:html>
<afh:head title="adfDataTable">
<meta http-equiv="Content-Type"
content="text/html; charset=windows-1252"/>
</afh:head>
<afh:body>
<h:form>
<af:table id="table1" value="#{PersonBkb.friendsList}" var="bkb"
width="600" rows="4" >
<f:facet name="selection">
<af:tableSelectMany text="Make a Bulk Selection">
</af:tableSelectMany>
</f:facet> 
<af:column sortable="true" headerNoWrap="true" headerText="" formatType="text">
<f:facet name="header">
<af:outputText value="No"/>
</f:facet>
<af:outputText value="#{bkb.lngID}"/>
</af:column> 
<af:column sortable="true" headerNoWrap="true" headerText="" formatType="number" sortProperty="strFirstName">
<f:facet name="header">
<af:outputText value="First Name"/>
</f:facet>
<af:outputText value="#{bkb.strFirstName}"/>
</af:column>
<af:column sortable="true" headerNoWrap="true" headerText="" formatType="text" sortProperty="strLastName">
<f:facet name="header">
<af:outputText value="Last Name"/>
</f:facet>
<af:outputText value="#{bkb.strLastName}"/>
</af:column>
<af:column sortable="true" headerNoWrap="true" headerText="" formatType="text" sortProperty="strCity">
<f:facet name="header">
<af:outputText value="Location"/>
</f:facet>
<af:outputText value="#{bkb.strCity}"/>
</af:column>
<af:column sortable="false" headerNoWrap="true" headerText="" formatType="text" sortProperty="strContactNo">
<f:facet name="header">
<af:outputText value="Contact"/>
</f:facet>
<af:outputText value="#{bkb.strContactNo}"/>
</af:column>
</af:table>
</h:form>
</afh:body>
</afh:html>
</f:view>

The Output will look like this…Can you find a difference ?



The above Output is the Adf Faces program output which provides rich set for all jsf components.




Added on April 8, 2008 Comment

Comments

#1

Div johns commented, on April 25, 2008 at 12:36 p.m.:

great jobs..
this is the exact thing i was looking for

#2

wodrof keins commented, on April 25, 2008 at 10:45 p.m.:

pritesh mistry
thanks for providing such a beautiful article.This will
be very much useful in our team. We were facing many difficulties while doing programming in jsf specially using
datatables.
we recommmad you to write same kind of article on jsf tree structure

#3

Raghu commented, on May 22, 2008 at 2:39 p.m.:

Database Connection Pooling is an Issue

#4

vidhyadharan commented, on June 27, 2008 at 1:02 p.m.:

Excellent article.. very much useful for my project
Continue this good job..

#5

priya commented, on July 4, 2008 at 4:56 p.m.:

Wonderful article.
It is very useful in my project.

Post a comment

Your name:

Comment: