2015-02-24 64 views
0

對於作業,我必須顯示從數據庫中提取的書籍的數據集,並且該表格必須在命令上可編輯,以便可以更新數據庫中的書籍條目。我的表,這是基於關閉的例子中,我們的教授做的代碼,是這樣的:爲什麼在方法調用之前不更新這個bean值?

  <h:dataTable value="#{bookList.inventory}" var="book" 
           rowClasses="oddrow, evenrow" headerClass="header"> 
     <h:column> 
      <f:facet name="header">ISBN</f:facet> 
      <h:inputText rendered="#{book.editable}" value="#{book.isbn}" /> 
      <h:outputText rendered="#{not book.editable}" 
          value="#{book.isbn}" /> 
     </h:column> 
     <h:column> 
      <f:facet name="header">Title</f:facet> 
      <h:inputText rendered="#{book.editable}" value="#{book.title}" /> 
      <h:outputText rendered="#{not book.editable}" 
          value="#{book.title}" /> 
     </h:column> 
     <h:column> 
      <f:facet name="header">Author</f:facet> 
      <h:inputText rendered="#{book.editable}" value="#{book.author}" /> 
      <h:outputText rendered="#{not book.editable}" 
          value="#{book.author}" /> 
     </h:column> 
     <h:column> 
      <f:facet name="header">Price</f:facet> 
      <h:inputText rendered="#{book.editable}" value="#{book.price}" /> 
      <h:outputText rendered="#{not book.editable}" 
          value="#{book.price}" /> 
     </h:column> 
     <h:column> 
      <h:commandLink 
       action="#{bookList.removeFromInventory(book)}" 
       value="Remove From Inventory"> 
       <f:ajax render="@form" /> 
      </h:commandLink> 
     </h:column> 
     <h:column> 
      <h:commandLink rendered="#{not book.editable}" 
          action="#{book.setEditable(not book.editable)}" value="Edit"> 
       <f:ajax render="@form" /> 
      </h:commandLink> 
      <h:commandLink rendered="#{book.editable}" 
          action="#{book.setEditable(not book.editable)}" value="Submit"> 
       <f:actionListener binding="#{bookList.updateEntry(book)}" /> 
       <f:ajax render="@form" /> 
      </h:commandLink> 
     </h:column> 
    </h:dataTable> 

然後updateEntry看起來是這樣的:

public void updateEntry(Book b) throws SQLException { 
    if(!b.getEditable()) return; 
    if(inventory == null) return; 
    if(ds == null) throw new SQLException("Can't connect to database"); 

    try(Connection conn = ds.getConnection()){ 
     PreparedStatement update = conn.prepareStatement("update books set " 
       + "title='" + b.getTitle() + "', Author='" + b.getAuthor() 
       + "', price=" + b.getPrice() + " where isbn=" +b.getIsbn()); 
     update.execute(); 

    } 
} 

的形式成功地變成可編輯的,而當我點擊提交updateEntry方法被調用正確。但是,它並沒有正確更新數據庫,因爲我通過調試發現,由於某種原因,它在調用updateEntry方法之前沒有更新變量簿。無論我在輸入中放入什麼,它都會將相同的值發送到updateEntry。我怎樣才能確保它在調用方法之前更新書中的值?

+0

小提示:要獲得工作分配的獎勵點,請檢查如何將outputText和inputText包裝在複合組件中 – Kukeltje 2015-02-24 23:40:13

回答

0

在對JSF何時調用setter方法進行更多研究之後找到了解決方案。因爲我沒有使用ajax屬性「execute」,所以在處理請求之前它沒有調用setter,因爲默認情況下只使用它包含的元素在渲染目標之前被處理。

的解決方案是我的ajax標籤改成這樣:

<f:ajax execute="@form" render="@form" /> 

我希望這能幫助別人努力學習JSF!

相關問題