作者: sealyu 日期:2009-05-06
在Seam中,如果要提供一個集合屬性傳到頁面,那么可以有兩種選擇:
(1).在SFSB中建一個集合屬性,并建立一個方法用來取得對應的數據。例如我們有一個SFSB(TestAction.java):
@Stateful
@Name("testPerson")
public class TestAction extends TestActionLocal implements Serializable{
protected List<Person> personList;
public List<Person> getPersonList(){
//得到對應數據
}
}
每次在前臺頁面調用的時候可以直接使用:
<rich:dataTable value="#{testPerson.personList}" id="xxx"/>.
但是這種方法有種缺點,因為將對應的值賦值給一個JSF組件,所以在刷新一個頁面的時候經常需要調用很多次取數據的函數,即使你作判斷(例如:當值不為空的時候不再重新取值),這個函數還是會執行很多次,可能會造成效率的問題。
但是這種方法的好處是總是可以取得最新的數據。在你經常通過傳遞參數來取得數據列表的時候,這種方法比較好。
(2).使用@Factory.
@Factory有兩種,在它的javadoc里面是這么說的:
* Marks a method as a factory method for a context variable.
* A factory method is called whenever no value is bound to
* the named context variable, and is expected to initialize
* the value of the context variable. There are two kinds of
* factory methods. Factory methods with void return type are
* responsible for outjecting a value to the context variable.
* Factory methods which return a value do not need to
* explicitly ouject the value, since Seam will bind the
* returned value to the specified scope.
第一種工廠方法:
這種工廠方法沒有返回值,但是你需要將得到的數據注出到context里面,大多數情況下你可以直接使用@DataModel,例如:
@Stateful
@Name("testPerson")
public class TestAction extends TestActionLocal implements Serializable{
@DataModel
protected List<Person> personList;
@Factory(value="personList", autoCreate=true)
public void getPersonList(){
//得到對應數據
this.personList=mgr.createQuery....
}
}
第二種工廠方法:
這種工廠方法有返回值,seam會根據scope的值將數據綁定到對應的上下文中。使用這種方法,你不用顯式的注出。例如:
@Stateful
@Name("testPerson")
public class TestAction extends TestActionLocal implements Serializable{
protected List<Person> personList;
@Factory(value="personList", autoCreate=true)
public List<Person> getPersonList(){
//得到對應數據
this.personList=mgr.createQuery....
return personList;
}
}
不管使用哪種方法,你都可以在頁面中直接訪問這個factory的值:
<rich:dataTable value="#{personList}" id="xxx"/>
使用@Factory的好處是不用重復的去取值,但是同時也有一個缺點:
使用@Factory的時候,只有在context中沒有這個@Factory所對應的綁定值的時候,seam才會重新執行工廠方法來取得這個值。所以如果你想要在CRUD一個實體之后更新列表的話,你可以監聽org.jboss.seam.afterTransactionSuccess.XXEntity事件來更新這個@Factory的值。暫時沒找到強制清空并刷新@Factory的方法,seam好像現在并沒有提供這個方法,所以我現在是直接清空@Factory所對應的list的值來達到刷新的目的。