Пример интеграции JSF 2.0 + JDBC
Вот руководство, чтобы показать вам, как интегрировать JSF 2.0 с базой данных через JDBC. В этом примере мы используем базу данных MySQL и веб-контейнер Tomcat.
Структура каталогов этого примера

1. Структура таблицы
Создайте таблицу «customer» и вставьте пять фиктивных записей. Позже отобразите его через JSFh:dataTable.
Команды SQL
DROP TABLE IF EXISTS `exampledb`.`customer`; CREATE TABLE `exampledb`.`customer` ( `CUSTOMER_ID` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, `NAME` varchar(45) NOT NULL, `ADDRESS` varchar(255) NOT NULL, `CREATED_DATE` datetime NOT NULL, PRIMARY KEY (`CUSTOMER_ID`) ) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8; insert into exampledb.customer(customer_id, name, address, created_date) values(1, 'example1', 'address1', now()); insert into exampledb.customer(customer_id, name, address, created_date) values(2, 'example2', 'address2', now()); insert into exampledb.customer(customer_id, name, address, created_date) values(3, 'example3', 'address3', now()); insert into exampledb.customer(customer_id, name, address, created_date) values(4, 'example4', 'address4', now()); insert into exampledb.customer(customer_id, name, address, created_date) values(5, 'example5', 'address5', now());
2. MySQL DataSource
Настройте источник данных MySQL с именем «jdbc/exampledb», следуйте этой статье -How to configure MySQL DataSource in Tomcat 6
3. Модельный класс
Создайте класс модели «Customer» для хранения записей таблицы.
Файл: Customer.java
package com.example.customer.model;
import java.util.Date;
public class Customer{
public long customerID;
public String name;
public String address;
public Date created_date;
//getter and setter methods
}
4. Пример JDBC
Управляемый компонент JSF 2.0, вводит источник данных «jdbc/exampledb» через@Resource и использует обычный JDBC API для извлечения всех записей клиентов из базы данных и сохранения их в списке.
Файл: CustomerBean.java
package com.example;
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;
import com.example.customer.model.Customer;
@ManagedBean(name="customer")
@SessionScoped
public class CustomerBean implements Serializable{
//resource injection
@Resource(name="jdbc/exampledb")
private DataSource ds;
//if resource injection is not support, you still can get it manually.
/*public CustomerBean(){
try {
Context ctx = new InitialContext();
ds = (DataSource)ctx.lookup("java:comp/env/jdbc/exampledb");
} catch (NamingException e) {
e.printStackTrace();
}
}*/
//connect to DB and get customer list
public List 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");
PreparedStatement ps
= con.prepareStatement(
"select customer_id, name, address, created_date from customer");
//get customer data from database
ResultSet result = ps.executeQuery();
List list = new ArrayList();
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"));
//store all data into a List
list.add(cust);
}
return list;
}
}
5. Таблица данных JSF
Страница JSF 2.0 xhtml используетh:dataTable для отображения всех записей клиентов в формате макета таблицы.
JSF 2.0 + JDBC Example
Customer ID
#{c.customerID}
Name
#{c.name}
Address
#{c.address}
Created Date
#{c.created_date}
6. Demo
Запустите его, посмотрите вывод

Скачать исходный код
Скачать -JSF-2-JDBC-Integration-Example.zip (12 КБ)