Java 怎么获取JSF组件绝对ID

2019年8月14日22:09:18 评论 37

1.简介

Java 怎么获取JSF组件绝对ID?——请看下文。

2.代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

 
import java.util.Iterator;
import javax.faces.component.NamingContainer;
import javax.faces.component.UIComponent;
import javax.faces.component.UINamingContainer;
import javax.faces.context.FacesContext;

public class Main{
    public static String getComponentAbsoluteId(UIComponent base,
            String targetId) {
        if (targetId == null || targetId.startsWith(":")) {
            return targetId;
        }
        String id = targetId;
        UIComponent target = findComponentFor(base, id);
        if (target != null) {
            id = getAbsoluteId(target);
        }
        return id;
    }
    public static UIComponent findComponentFor(UIComponent component,
            String id) {
        if (id == null) {
            throw new NullPointerException("id is null!");
        }
        if (id.length() == 0) {
            return null;
        }
        UIComponent target = null;
        UIComponent parent = component;
        UIComponent root = component;
        while (target == null && parent != null) {
            target = findUIComponentBelow(parent, id);
            root = parent;
            parent = parent.getParent();
        }
        if (target == null) {
            target = findUIComponentBelow(root, id);
        }
        return target;
    }
    public static String getAbsoluteId(UIComponent component) {
        StringBuffer idBuf = new StringBuffer();
        idBuf.append(component.getId());
        UIComponent parent = component;
        char sep = UINamingContainer.getSeparatorChar(FacesContext
                .getCurrentInstance());

        while ((parent = parent.getParent()) != null) {
            if (parent instanceof NamingContainer) {
                idBuf.insert(0, sep);
                idBuf.insert(0, parent.getId());
            }
        }
        idBuf.insert(0, sep);
        return idBuf.toString();
    }
    protected static UIComponent findUIComponentBelow(UIComponent root,
            String id) {
        UIComponent target = null;
        for (Iterator<UIComponent> iter = root.getFacetsAndChildren(); iter
                .hasNext();) {
            UIComponent child = iter.next();
            if (child instanceof NamingContainer) {
                try {
                    target = child.findComponent(id);
                } catch (IllegalArgumentException iae) {
                    continue;
                }
            }
            if (target == null && child.getChildCount() > 0) {
                target = findUIComponentBelow(child, id);
            }
            if (target != null) {
                break;
            }
        }
        return target;
    }
}

 

3.总结

示例代码演示了 Java 怎么获取JSF组件绝对ID,具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: