Friday, February 12, 2010

Writing Facelets Composite Component in JSF 2.0

JSF 2.0 is making it easier for Java EE web developers to write composite components.

Composite components are reusable custom HTML fragments + presentation logic.

I said "easier" because in JSF 1.x it was horrible. Now it's manageable, but not necessarily easier than other frameworks, like Tapestry or Wicket. At least it can compete on a similar level.

To create a composite component, write a view using Facelets XHTML like this example:
<?xml version='1.0' encoding='UTF-8' ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"

      xmlns:composite="http://java.sun.com/jsf/composite">

    <composite:interface>

        <composite:attribute name="title" required="true" />

    </composite:interface>

    <composite:implementation>

        <div style="background: red; color: yellow">

            #{cc.attrs.title}

        </div>

        <div style="border: 1px solid green">

            <composite:insertChildren />

        </div>

    </composite:implementation>

</html>
Save the XHTML code above as resources/ezcomp/titleBorder.xhtml.

Composite components live under resources folder, and the namespace will be determined from the subfolder name.

Use the ezcomp:titleBorder component like this:
<?xml version='1.0' encoding='UTF-8' ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"

      xmlns:h="http://java.sun.com/jsf/html"

      xmlns:ezcomp="http://java.sun.com/jsf/composite/ezcomp">

    <h:head>

        <title>Composite Component Demo</title>

    </h:head>

    <h:body>

        <ezcomp:titleBorder title="Cool stuff">

            So happy to be here!

        </ezcomp:titleBorder>

    </h:body>

</html>
Not bad, is it? ;-)

Related posts: