2010年的最后一天写了一个JSF2与JDBC集成的例子,记录一下。
准备数据库表创建:
SQL> create table customer(
2 id number(8) not null primary key,
3 name varchar2(20),
4 age number(3),
5 gender varchar2(8)
6 );
insert into customer(id,name,age,gender) values (1,'zhanghong',1,'male');
insert into customer(id,name,age,gender) values (2,'zhanghong2',2,'female');
insert into customer(id,name,age,gender) values (3,'zhanghong3',3,'male');
insert into customer(id,name,age,gender) values (4,'zhanghong4',4,'female');
定义POJO:
public class Customer {
private long id;
private String name;
private int age;
private String sex;
.........
}
@ManagedBean(name = "userBean")
@RequestScoped
public class UserBean {
.....................
private List<Customer> customers;
@Resource(name = "jdbc/oracleDateSource")
private DataSource dataSource;
public List<Customer> getCustomers() throws SQLException{
if (dataSource == null)
throw new SQLException("Can't get data source");
// get database connection
Connection con = dataSource.getConnection();
if (con == null)
throw new SQLException("Can't get database connection");
PreparedStatement ps = con
.prepareStatement("select id, name,age,gender from customer");
// get customer data from database
ResultSet result = ps.executeQuery();
List<Customer> list = new ArrayList<Customer>();
while (result.next()) {
Customer customer = new Customer();
application.setId(result.getLong("id"));
application.setName(result.getString("name"));
application.setAge(result.getInt("age"));
application.setSex(result.getString("gender"));
// store all data into a List
list.add(customer);
}
return list;
}
public void setApplications(List<Customer> customers) {
this.customers = customers;
}
页面:
<h:dataTable value="#{userBean.customers}" var="a" styleClass="data-table"
headerClass="tableHeader" rowClasses="odd,even" >
<h:column>
<f:facet name="header">
<h:outputText value="ID"></h:outputText>
</f:facet>
<h:outputText value="#{a.id}"></h:outputText>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="NAME"></h:outputText>
</f:facet>
<h:outputText value="#{a.name}"></h:outputText>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="AGE"></h:outputText>
</f:facet>
<h:outputText value="#{a.age}"></h:outputText>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="SEX"></h:outputText>
</f:facet>
<h:outputText value="#{a.sex}"></h:outputText>
</h:column>
</h:dataTable>
页面效果: