JSF JDBC設置示例

2018-02-22 14:28 更新

JSF教程 - JSF JDBC設置示例


以下代碼顯示如何從后端數據庫加載數據并使用JSF顯示數據。

例子

以下代碼來自Customer.java。

package cn.w3cschool.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;
  }
}

以下代碼來自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;
}

以下代碼來自CustomerBean.java。

package cn.w3cschool.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/w3cschool")
  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/w3cschool");
    } 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","w3cschool","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;
  }
}

以下代碼來自context.xml。

<Context>
<!--
  <Resource name="jdbc/w3cschool" 
            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/w3cschool"/>

-->
  <Resource name="jdbc/w3cschool" 
            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>

以下代碼來自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>
下載 JDBC_Setup.zip

運行

將生成的WAR文件從目標文件夾復制到Tomcat部署文件夾,并運行Tomcat-Install-folder/bin/startup.bat。

Tomcat完成啟動后,在瀏覽器地址欄中鍵入以下URL。

http://localhost:8080/simple-webapp/default.xhtml
以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號