EJB+JSF+SEAM 使用Richfaces中的Tree和TreeNode組件
Entity部分關鍵代碼:
public class PartType {
//屬性...
private PartType parent;
private Set<PartType> children = new HashSet<PartType>();
//屬性對應的getter、setter......
@ManyToOne
public PartType getParent() {
return parent;
}
public void setParent(PartType parent) {
this.parent = parent;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "parent")
public Set<PartType> getChildren() {
return children;
}
public void setChildren(Set<PartType> children) {
this.children = children;
}
public void addChildren(PartType pt) {
this.children.add(pt);
}
}
SessionBean代碼......
Action部分關鍵代碼:
@Name("ptAction")
@Scope(ScopeType.CONVERSATION)
public class PartTypeAction {
@Logger
private Log log;
@In
private IPartTypeManager ptManager;
@Out(required = false)
private PartType selectpt;
public PartType getSelectpt() {
return selectpt;
}
public void setSelectpt(PartType selectpt) {
this.selectpt = selectpt;
}
/*
* 遞歸節點樹
*/
private TreeNode<PartType> addChild(TreeNode<PartType> curNode,
PartType curPT) {
curNode.setData(curPT);
log.info("遍歷: " + curPT.getName());
if (curPT.getChildren().size() > 0) {
for (Iterator iterator = curPT.getChildren().iterator(); iterator
.hasNext();) {
PartType childptItem = (PartType) iterator.next();
TreeNode<PartType> childpt = new TreeNodeImpl<PartType>();
curNode.addChild(childptItem.getId(), childpt);// 子節點加到當前節點下
addChild(childpt, childptItem);
}
}
return curNode;
}
/*
* 構建樹
*/
@Begin(join = true)
public TreeNode<PartType> getPTTree() {
log.info("構建PartType Tree");
PartType ptroot = ptManager.getRootPartType();//調用SessionBean中的方法以獲取父節點
TreeNode<PartType> root = new TreeNodeImpl<PartType>();
this.addChild(root, ptroot);
TreeNode<PartType> vroot = new TreeNodeImpl<PartType>();
vroot.addChild(root.getData().getId(), root);
return vroot;
}
/*
* 選擇一個節點觸發事件
*/
@Begin(join = true)
public void processSelection(NodeSelectedEvent event) {
UITree tree = getTree(event);
if (tree != null) {
selectpt = (PartType) tree.getTreeNode().getData();
log.info("選中節點:" + selectpt.getName());
this.setSelectpt(selectpt);
}
}
private UITree getTree(FacesEvent event) {
UIComponent component = event.getComponent();
if (component instanceof UITree) {
return ((UITree) component);
}
if (component instanceof UITreeNode) {
return ((UITree) component.getParent());
}
return null;
}
}
頁面代碼:
<rich:tree swidth="100%" value="#{ptAction.PTTree}" var="item" switchType="ajax" reRender="userdata" nodeSelectListener="#{ptAction.processSelection}" ajaxSubmitSelection="true"> <rich:treeNode> <h:outputText value="#{item.name}" /> </rich:treeNode> </rich:tree>