|
The most powerful feature of JSP is that - the user can also create their own custom tags. The servlet API contains the javax.servlet.jsp.tagext.BodyTagSupport class, which is used to create the custom tags. All the tags need to extend the javax.servlet.jsp.tagext.BodyTagSupport class and override doStartTag(), doEndTag() and doAfterBody() methods. After creating the Java class for the custom tag, the tag library description file is to be created. The extension for the XML description file is .tld. The following example will create a tag, which takes String and prints the reverse of the String when displayed on the browser.
ReverseTag.java
package com.visualbuilder.taglibrary;
import java.io.IOException;
import javax.servlet.jsp.JspTagException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.BodyContent; import javax.servlet.jsp.tagext.BodyTagSupport;
public class ReverseTag extends BodyTagSupport {
/** * */ private static final long serialVersionUID = 1L;
public int doStartTag() throws JspTagException{ return EVAL_BODY_TAG; } public int doEndTag() throws JspTagException { try { JspWriter out = pageContext.getOut(); } catch (Exception ex) { throw new JspTagException("All is not well in the world." + ex); } return SKIP_BODY; }
public int doAfterBody() throws JspTagException {
BodyContent body = getBodyContent(); try { // Make sure we put anything in the output stream in the // body to the output stream of the JSP JspWriter out = body.getEnclosingWriter(); String bodyContent = body.getString(); if (bodyContent != null) { for (int i = bodyContent.length() - 1; i >= 0; i--) { out.print(bodyContent.charAt(i)); } } out.println(); body.clearBody(); // Clear for next evaluation } catch (IOException ioe) { throw new JspTagException("Error in reverse tag doAfterBody " + ioe); } return (SKIP_BODY);
} } |