Using EL expression with a custom tag
November 21, 2011 13:49:11 Last update: November 21, 2011 13:49:11
In the test for the simple taglib example, I used a literal string for the name attribute:
What happens if the name attribute contains EL expresson? For example:
If EL works, the tag should take the value of the "
In order to make a tag to recognize EL, we have to use
The
Rebuild the taglib and test with a URL like this:
The tag will print:
<my:hello name="Jack"/>
What happens if the name attribute contains EL expresson? For example:
<my:hello name="#{param['name']}"/>
If EL works, the tag should take the value of the "
name" request parameter and print it out. But the tag as implemented in the simple taglib example prints the literal string:
Hello #{param['name']}! I am FaceletTag.
In order to make a tag to recognize EL, we have to use
TagAttribute.getValue(FaceletContext ctx) instead of TagAttribute.getValue(). The latter returns the literal value of the attribute.
The
HelloTagHandler should be changed to:
package com.example; import java.io.IOException; import javax.faces.component.UIComponent; import javax.faces.component.UIComponentBase; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import javax.faces.view.facelets.FaceletContext; import javax.faces.view.facelets.TagAttribute; import javax.faces.view.facelets.TagHandler; import javax.faces.view.facelets.TagConfig; /** * Custom facelet tag that says hello. */ public class HelloTagHandler extends TagHandler { private String name = "Anonymous"; public HelloTagHandler(TagConfig config) { super(config); } public void apply(FaceletContext context, UIComponent parent) throws IOException { TagAttribute a = tag.getAttributes().get("name"); if (a != null) { name = a.getValue(context); // this call evaluates EL } UIComponentBase c = new UIComponentBase() { public void encodeEnd(FacesContext ctx) throws IOException { ResponseWriter w = ctx.getResponseWriter(); w.write(String.format( "<p>Hello %s! I am FaceletTag.</p>", name )); } // abstract method in base, must override public String getFamily() { return "com.example.facelettag.test"; } }; parent.getChildren().add(c); } }
Rebuild the taglib and test with a URL like this:
http://localhost:8080/facelet-test/?name=Jack
The tag will print:
Hello Jack! I am FaceletTag.