You implement the functions of your simple tags in tag handler classes. A simple tag handler class implements the javax.servlet.jsp.tagext.SimpleTagSupport interface.
...
1. Create a class that extends the javax.servlet.jsp.tagext.SimpleTagSupport interface.
2. Optionally, in the class define a set of properties in a JavaBeans manner (class variables with getter and setter methods).
3. Override the doTag() method of SimpleTagSupport defining the required behavior of your custom tag.
We want to create a custom tag that generates a simple HTML table.
With this simple tag handler we use javax.servlet.jsp.JspContext, unlike with classic tag handlers, which use javax.servlet.jsp.PageContext.
getJspContext().getOut().write(tableString); |
We write the body of the tag in the output. Here, the body is instance of class javax.servlet.jsp.tagext.JspFragment.
getJspBody().invoke(getJspContext().getOut()); |
The complete source code is the following:
package com.sap.demo.exampletags;
import java.io.IOException; import java.text.MessageFormat; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspTagException; import javax.servlet.jsp.tagext.SimpleTagSupport;
public class HelloWorldTag extends SimpleTagSupport{
private static final long serialVersionUID = 956562171591119686L; private String bgcolor; private String title;
public String getBgcolor() { return bgcolor; }
public void setBgcolor(String bgcolor) { this.bgcolor = bgcolor; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
@Override public void doTag() throws JspException, IOException { try { String tableString = MessageFormat.format( "<table border=\"1\"><tr><td><b>{0}</b></td></tr><tr><td bgcolor=\"{1}\">", getTitle(), getBgcolor()); getJspContext().getOut().write(tableString); getJspBody().invoke(getJspContext().getOut()); getJspContext().getOut().write("</td></tr></table>"); } catch(IOException e) { throw new JspTagException("IO Error: " + e.getMessage()); } } } |