Followers

JSP:Custom Tags (BodyTagSupport)

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

 Welcome to this application
 <br ><br >
<mytags:cap>
    Hello
    <br ><br >
    how are you?
    <br ><br >
    I hope you are fine.
</mytags:cap>

<mytags:filterbad>
    <br ><br >
    dear client you are very bad
    <br ><br >
    because you do bad things.
   
</mytags:filterbad>
    <br ><br >
    BYE, BYE

FilterBadTag.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 FilterBadTag extends BodyTagSupport{
 
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("bad")){
                token = "good";
                }
         filteredtext = filteredtext+" "+token;
        }
      out.println(filteredtext);
    } catch (IOException ex) {    }
    return (SKIP_BODY);
   
}
}



CapTag.java
============
package com.java9m.mohan;
import java.io.IOException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.*;
public class CapTag extends BodyTagSupport{
 
public int doAfterBody(){
    try {
        BodyContent body = getBodyContent();
        String text = body.getString();
        text= text.toUpperCase();
        JspWriter out = body.getEnclosingWriter();
        out.println(text);
    } 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>cap</name>
    <tag-class>com.java9m.mohan.CapTag</tag-class>
  </tag>
  <tag>
    <name>filterbad</name>
    <tag-class>com.java9m.mohan.FilterBadTag</tag-class>
  </tag>
</taglib>






No comments:

Post a Comment