2014-01-20 43 views
1

我找到了一些參考JSF Parameter Passing參數在JSF 2.0中傳遞

但是,這是不正常的我的要求。我會將object(Student)一個支持bean傳遞給另一個bean,如下所示。

studentTable.xhtml        updateStudent.xhtml 
         pass student object 
         (not `StudentID` string) 
         ==================> 
StudentTableBean.java       UpdateStudnetBean.java 

兩個輔助bean可以是RequestScopeViewScope,不Session。當我點擊鏈接(一行數據表)studentTable.xhtml時,我想將學生對象傳遞給updateStudent.xhtml

可能嗎?你能否提供一些參考或提供?

回答

0

你會怎麼想呢? Viewscope在離開頁面時結束,並且該範圍內的所有Bean都被銷燬 - 它們所持有的對象也會被銷燬。

updateStudent.xhtml創建一個新視圖並獲取它自己的Viewscoped組。如果要在頁面之間保留對象,請啓動一個新的,長時間運行的對話或將對象推入會話範圍。

關於使用對話範圍,請參閱this tutorial

+0

我在我的項目中使用'Jboss Seam'。現在我正在考慮刪除'Jboss Seam'。這就是爲什麼,我想研究像'對話'。 – CycDemo

+0

@CycDemo我處於相同的位置,並選擇了ViewScoped beans和轉換器,如下面所示的BalusC(ConversationScoped是JEE7添加,但我不確定)。由於所有查找都是通過PK進行的,因此它們非常容易緩存,並且與JSF需要做的其他所有工作相比,應該閃電般快速。 – mabi

0

您可以通過將學生的對象放入請求的當前實例的會話映射中來做到這一點:您將有問題的學生的ID從studentTable.xhtml傳遞給支持bean UpdateStudnetBean.java,然後搜索對象實例從資源(列表,數據庫等),然後你把它放在上面的會話映射對象中。通過這種方式,您可以 通過隱式對象sessionScope將其置於視圖updateStudent.xhtml中。

2

HTTP和HTML不理解複雜的Java對象。在Java透視圖中,他們只理解字符串。您最好將複雜的Java對象轉換爲字符串flavor中的唯一標識符,通常是其技術ID(例如,自動生成的數據庫PK),並將該標識符用作HTML鏈接中的HTTP請求參數。

給定一個List<Student>主要內容如下表示爲表的鏈接,

<h:dataTable value="#{studentTable.students}" var="student"> 
    <h:column> 
     <h:link value="Edit" outcome="updateStudent.xhtml"> 
      <f:param name="id" value="#{student.id}" /> 
     </h:link> 
    </h:column> 
</h:dataTable> 

您可以在目標視圖updateStudent.xhtml使用<f:viewParam>到通過學生ID轉換回Student如下,

<f:metadata> 
    <f:viewParam name="id" value="#{updateStudent.student}" converter="#{studentConverter}" /> 
</f:metadata> 

private Student student; 

and

@ManagedBean 
@ApplicationScoped 
public class StudentConverter implements Converter { 

    @EJB 
    private StudentService studentService; 

    @Override 
    public Object getAsObject(FacesContext context, UIComponent component, String value) { 
     if (value == null || value.isEmpty()) { 
      return null; 
     } 

     if (!value.matches("[0-9]+")) { 
      throw new ConverterException("The value is not a valid Student ID: " + value); 
     } 

     long id = Long.valueOf(value); 
     return studentService.getById(id); 
    } 

    @Override  
    public String getAsString(FacesContext context, UIComponent component, Object value) {   
     if (value == null) { 
      return ""; 
     } 

     if (!(value instanceof Student)) { 
      throw new ConverterException("The value is not a valid Student instance: " + value); 
     } 

     Long id = ((Student)value).getId(); 
     return (id != null) ? String.valueOf(id) : null; 
    } 

} 
+0

傳遞'ID String',再次從DB中檢索。否則,使用'SessionScope'或'ApplicationScope'。我對嗎?感謝您的提供。 – CycDemo

+0

不要濫用範圍,否則你會殺死threadsafety和用戶體驗。進一步閱讀:http://stackoverflow.com/q/7031885和http://stackoverflow.com/a/15523045更有幫助的鏈接:https://jsf.zeef.com/bauke.scholtz – BalusC