Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
779 views
in Technique[技术] by (71.8m points)

jsf 2 - Custom Facelet component in JSF

Is it possible to create a custom JSF core Facelet component. Something like <custom:composition> of <ui:composition>, or <custom:include> for <ui:include> It would be helpful if someone can tell me the steps involved.

Thanks in advance,

Kaushal

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It are in essence taghandlers. I.e. classes extending from TagHandler.

Here's a Hello World taghandler.

com.example.HelloTagHandler

public class HelloTagHandler extends TagHandler {

    public HelloTagHandler(TagConfig config) {
        super(config);
    }

    @Override
    public void apply(FaceletContext context, UIComponent parent) throws IOException {
        // Do your job here. This example dynamically adds another component to the parent.
        if (ComponentHandler.isNew(parent)) {
            UIOutput child = new HtmlOutputText();
            child.setValue("Hello World");
            parent.getChildren().add(child);
        }

        nextHandler.apply(context, parent); // Delegate job further to first next tag in tree hierarchy.
    }

}

/WEB-INF/my.taglib.xml

<?xml version="1.0" encoding="UTF-8"?>
<facelet-taglib
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facelettaglibrary_2_0.xsd"
    version="2.0"
>
    <namespace>http://example.com/my</namespace>
    <tag>
        <tag-name>hello</tag-name>
        <handler-class>com.example.HelloTagHandler</handler-class>
    </tag>
</facelet-taglib>

/WEB-INF/web.xml (note: this part is not mandatory when my.taglib.xml is in /META-INF folder of a JAR file inside /WEB-INF/lib like as with JSF component libraries):

<context-param>
    <param-name>javax.faces.FACELETS_LIBRARIES</param-name>
    <param-value>/WEB-INF/my.taglib.xml</param-value>
</context-param>

Usage in /some.xhtml

<html ... xmlns:my="http://example.com/my">
...
<my:hello />

To see the source code of Mojarra implementation of <ui:composition> and <ui:include>, click the links.

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...