Followers

JSP:Custom Tags (BodyTagSupport with parameters)

first.jsp
=========
<%@ taglib uri="WEB-INF/mytags.tld" prefix="mytags" %>

Hello how are you?
 <br ><br >
 Welcome to this application
 <br ><br >


 <mytags:filter replace="Clients" with="Students">
    <br ><br >
    Dear Clients
    <br ><br >
</mytags:filter>

    <mytags:filter replace="day" with="minute" >
    I wish every day is more colorful.
    <br ><br >
    Every day is successful.
    <br ><br >
       
    </mytags:filter>
    <mytags:filter replace="start" with="end" >
        This is the start of advanced java.
    </mytags:filter>
   
    <br ><br >
    BYE, BYE
    <br ><br >
        I am missing you ALL.  
    <br ><br >
   
    <b>
    We will meet again next weekend for Spring.
    </b>

FilterTag.java
===============

package com.java9m.mohan;
import java.io.IOException;
import java.util.StringTokenizer;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.*;
import static javax.servlet.jsp.tagext.Tag.SKIP_BODY;
public class FilterTag extends BodyTagSupport{
    String replace;
    String with;

    public void setReplace(String replace) {
        this.replace = replace;
    }

    public void setWith(String with) {
        this.with = with;
    }
public int doAfterBody(){
    String filteredtext = "";
    try {
        BodyContent body = getBodyContent();
        String text = body.getString();
        JspWriter out = body.getEnclosingWriter();
        StringTokenizer st = new StringTokenizer(text);
        while(st.hasMoreTokens()){
            String token = st.nextToken();
                if(token.equalsIgnoreCase(replace)){
                token = with;
                }
         filteredtext = filteredtext+" "+token;
        }
      out.println(filteredtext);
    } catch (IOException ex) {    }
    return (SKIP_BODY);
   
}
}
mytags.tld
===========

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">

<taglib>
  <tlib-version>1.0</tlib-version>
  <jsp-version>1.2</jsp-version>
  <short-name>simple</short-name>
  <tag>
    <name>filter</name>
    <tag-class>com.java9m.mohan.FilterTag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <name>replace</name>
        <required>true</required>
    </attribute>
    <attribute>
        <name>with</name>
        <required>true</required>
    </attribute>
   
  </tag>
</taglib>



No comments:

Post a Comment