【问题标题】:JSF DataTable not displaying databaseJSF DataTable 不显示数据库
【发布时间】:2015-03-18 08:50:45
【问题描述】:

我遇到了一种方法,可以在网站上显示我的数据库中的数据。但是,我遵循了一个示例,即创建一个 bean,在我要显示的页面上创建一个数据表,但是当我运行网站时,它只打印出 bean 的字符串。我该如何纠正这个问题?

index.xhtml

<h:dataTable value="#{addressBean.addresses}" var="address" rowClasses="oddRows,evenRows" headerClass="header" styleClass="table" cellpadding="5" cellspacing="0">
  <h:column>
    <f:facet name="header">First Name</f:facet>
    #{address.FIRSTNAME}
  </h:column>
  <h:column>
    <f:facet name="header">Last Name</f:facet>
    #{address.LASTNAME}
  </h:column>
  <h:column>
    <f:facet name="header">Street</f:facet>
    #{address.STREET}
  </h:column>
  <h:column>
    <f:facet name="header">City</f:facet>
    #{address.CITY}
  </h:column>
  <h:column>
    <f:facet name="header">State</f:facet>
    #{address.STATE}
  </h:column>
  <h:column>
    <f:facet name="header">Zip code</f:facet>
    #{address.ZIP}
  </h:column>
</h:dataTable>

AddressBean.java

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.sql.DataSource;
import javax.sql.rowset.CachedRowSet;

@
ManagedBean(name = "addressBean")
public class AddressBean {
  // instance variables that represent one address
  private String firstName;
  private String lastName;
  private String street;
  private String city;
  private String state;
  private String zipcode;

  // allow the server to inject the DataSource
  @
  Resource(name = "jdbc/addressbook")
  DataSource dataSource;

  // get the first name
  public String getFirstName() {
      return firstName;
    } // end method getFirstName

  // set the first name
  public void setFirstName(String firstName) {
      this.firstName = firstName;
    } // end method setFirstName

  // get the last name
  public String getLastName() {
      return lastName;
    } // end method getLastName

  // set the last name
  public void setLastName(String lastName) {
      this.lastName = lastName;
    } // end method setLastName

  // get the street
  public String getStreet() {
      return street;
    } // end method getStreet

  // set the street
  public void setStreet(String street) {
      this.street = street;
    } // end method setStreet

  // get the city
  public String getCity() {
      return city;
    } // end method getCity

  // set the city
  public void setCity(String city) {
      this.city = city;
    } // end method setCity

  // get the state
  public String getState() {
      return state;
    } // end method getState

  // set the state
  public void setState(String state) {
      this.state = state;
    } // end method setState

  // get the zipcode
  public String getZipcode() {
      return zipcode;
    } // end method getZipcode

  // set the zipcode
  public void setZipcode(String zipcode) {
      this.zipcode = zipcode;
    } // end method setZipcode

  // save a new address book entry
  public String save() throws SQLException {
      // check whether dataSource was injected by the server
      if (dataSource == null)
        throw new SQLException("Unable to obtain DataSource");

      // obtain a connection from the connection pool
      Connection connection = dataSource.getConnection();

      // check whether connection was successful
      if (connection == null)
        throw new SQLException("Unable to connect to DataSource");

      try {
        // create a PreparedStatement to insert a new address book entry
        PreparedStatement addEntry =
          connection.prepareStatement("INSERT INTO ADDRESSES " +
            "(FIRSTNAME,LASTNAME,STREET,CITY,STATE,ZIP)" +
            "VALUES ( ?, ?, ?, ?, ?, ? )");

        // specify the PreparedStatement's arguments
        addEntry.setString(1, getFirstName());
        addEntry.setString(2, getLastName());
        addEntry.setString(3, getStreet());
        addEntry.setString(4, getCity());
        addEntry.setString(5, getState());
        addEntry.setString(6, getZipcode());

        addEntry.executeUpdate(); // insert the entry
        return "index"; // go back to index.xhtml page
      } // end try
      finally {
        connection.close(); // return this connection to pool
      } // end finally
    } // end method save

  // return a ResultSet of entries
  public ResultSet getAddresses() throws SQLException {
      // check whether dataSource was injected by the server
      if (dataSource == null)
        throw new SQLException("Unable to obtain DataSource");

      // obtain a connection from the connection pool
      Connection connection = dataSource.getConnection();

      // check whether connection was successful
      if (connection == null)
        throw new SQLException("Unable to connect to DataSource");

      try {
        // create a PreparedStatement to insert a new address book entry
        PreparedStatement getAddresses = connection.prepareStatement(
          "SELECT FIRSTNAME, LASTNAME, STREET, CITY, STATE, ZIP " +
          "FROM ADDRESSES ORDER BY LASTNAME, FIRSTNAME");

        CachedRowSet rowSet = new com.sun.rowset.CachedRowSetImpl();
        rowSet.populate(getAddresses.executeQuery());
        return rowSet;
      } // end try
      finally {
        connection.close(); // return this connection to pool
      } // end finally
    } // end method getAddresses
} // end class AddressBean

数据库 SQL

DROP TABLE Addresses;

CREATE TABLE Addresses
(
	AddressID INT NOT NULL GENERATED ALWAYS AS IDENTITY,
	FirstName VARCHAR (30) NOT NULL,
	LastName VARCHAR (30) NOT NULL,
	Street VARCHAR (150) NOT NULL,
	City VARCHAR (30) NOT NULL,
	State VARCHAR (2) NOT NULL,
	Zip VARCHAR (5) NOT NULL,
	PRIMARY KEY (AddressID)
);

INSERT INTO Addresses (FirstName,LastName,Street,City,State,Zip) VALUES 
   ('Bob','Green','5 Bay St.','San Francisco','CA','94133'),
   ('Liz','White','100 5th Ave.','New York','NY','10011'),
   ('Mike','Brown','3600 Delmar Blvd.','St. Louis','MO','63108'),
   ('Mary','Green','300 Massachusetts Ave.','Boston','MA','02115'),
   ('John','Gray','500 South St.','Philadelphia','PA','19147'),
   ('Meg','Gold','1200 Stout St.','Denver','CO','80204'),
   ('James','Blue','1000 Harbor Ave.','Seattle','WA','98116'),
   ('Sue','Black','1000 Michigan Ave.','Chicago','IL','60605');

【问题讨论】:

    标签: java jsf


    【解决方案1】:

    首先,我将创建一个新的托管 bean,它可能是 @ViewScoped,它有一个 AddressBean 对象列表(不要忘记 getter/setter):

    private ArrayList <AddressBean> addresses = new ArrayList <AddressBean>();
    

    然后我会将您的 getAddresses() 方法移动到这个新 bean 并对其进行更改,以便它遍历您的查询的 ResultSet,创建 AddressBean 对象,然后将它们添加到地址 ArrayList。然后我会在新的“View Bean”的构造函数中调用getAddresses() 方法,以便在实例化 bean 时加载数据库中的地址。

    注意:所以有一个带有getter/setter 的AddressBean 托管bean,然后是另一个“View Bean”,它调用该方法来加载数据库记录并将AddressBean 对象存储在ArrayList 中。以及使用数据库、Java 和 Web 级别(数据访问层、业务层和 UI bean 层等)之间的集成层来构建您的项目。

    您在 xhtml 中的数据表将从:

    <h:dataTable value="#{addressBean.addresses}" var="address" rowClasses="oddRows,evenRows" headerClass="header" styleClass="table" cellpadding="5" cellspacing="0">
    

    收件人:

    <h:dataTable value="**#{addressViewBean.addresses}**" var="address" rowClasses="oddRows,evenRows" headerClass="header" styleClass="table" cellpadding="5" cellspacing="0">
    

    编辑:针对您的评论,您可以执行以下操作:

    在上述“View bean”的顶部声明一个带有 getter/setter 的 AddressBean 对象:

    private AddressBean addressBean;
    

    然后在连接到数据库并加载记录的视图 bean 方法中,执行以下操作....

    while(rowSet.next())
    {
        addressBean= new AddressBean(rowSet.getString("FirstName"), rowSet.getString("LastName"), rowSet.getString("Street"), rowSet.getString("City"), rowSet.getString("State"), rowSet.getString(("Zip"));
        addresses.add(addressBean);
    }
    

    把上面的代码放在后面

     rowSet.populate(getAddresses.executeQuery());
    

    并将返回类型更改为 void。

    【讨论】:

    • 好的。我无法理解的问题是从数据库中加载记录并将其保存到数组列表中。你能简化一下吗?
    猜你喜欢
    • 2010-11-27
    • 1970-01-01
    • 2011-05-15
    • 2018-02-15
    • 2021-06-13
    • 1970-01-01
    • 2020-05-12
    • 1970-01-01
    • 2018-11-09
    相关资源
    最近更新 更多