JaiswalTraining

Get the online training



Corejava Servlet Jsp  Php  Hibernate  Ajax Web Service   Ejb2.1 Ejb3.0 Struts Struts2  JPA Spring Ibatis   JSF    JSF2.0  CoreJavaDesignPattern    Jquery  Flex J2EE-Design-Patterns  Jboss7  Maven  Contact Me                                                                                                                                                                        
            IGNOU SMU PTU Project                                           Training                                                                                                                              
              

Contact Us  0091- 9210721663         jaiswaltraining@gmail.com




Corejava
Servlet
Jsp
Php
Hibernate
Ajax
Web Service
Ejb2.1
Ejb3.0
Struts  
Struts2
JPA
Spring
Ibatis
JSF
JSF2.0
CoreJavaDesignPattern
Jquery
Flex
J2EE-Design-Patterns
Jboss7
Maven







Creating Custom JSP Tag Libraries: The Basics

  • It is used to separate the presentation and business logic.
  • It is used to encapsulate the complex programming code in a tag.
  • Custom tags are reusable.

The Tag library

  • Consists of a collection of functionally related, user-defined tags called custom tags.
  • Custom Tag
    • Custom tags are user-defined and explicitly render information about the type of data.
    • Are very similar to XML tags.
    • Allows interactions between the user and the browser.
    • Facilitates reuse of existing codes to improve work productivity
Tag Structure
  •  It should have start and end tag with body.
  • It can be of two types.
    • Body Tags.
    • Empty Tags.
  • One tag can contain another tag.
  • Tag can have the attributes passed as parameter.

  • It consists of two  parts
    • Tag Handler
    • Tag Library Descriptor File(TLD).
Tag Handler

  • This class has  definition of  classes and methods.
  • It defines the functionality of the tag.
  • It uses  methods from the javax.servlet.tagext package.
  • Implements the TagSupport interface for tags with an empty body.
  • Implements the BodyTagSupport interface for tags that use a body
  • Also includes classes from other packages, such as javax.servlet.jsp and java.io 

Tag Library Descriptor File(TLD)
  • This is a xml file.
  • It has description, name version and other value for  custom tag.
  • It has to be creaated inside the WEB-INF.
 The JSP File 
  •  Imports a tag library (referencing URL of descriptor file)
  •  Defines tag prefix
  •  Uses tags.
Tag Handler  Usage with Different tags

  • It can bed used for basic tag, a tag with attributes and 
  • A tag with body.
Simple Tag with no body and no attributes
  • It has methods
    • doStartTag()
    • doEndTag()
    • release()
Tag with attributes
  • It has methods
    • doStartTag()
    • doEndTag()
    • and set and get methods. for each tag.
Defining a Custom Tag Handler

  • Simple tag handlers implement the SimpleTag interface. 
  • So first extend the SimpleTagSupport class
  • Then  import required package.
        import javax.servlet.jsp.*;
        import javax.servlet.jsp.tagext.*;
        import java.io.*;


  •  Override doTag
    •  Obtain the JspWriter with getJspContext().getOut()
    •  Use the JspWriter to generate output
    •  Code gets called at request time
    • Tag instances are not reused like servlet instances, so no worry about race conditions, even if you have instance variables.

Building your first custom jsp tag

1. Write the Tag Handler class
2. Create the tag library descriptor (TLD)
3. Use tag in jsp file


Creating Custom  tag project  in Eclipse

  • First we will create one Dynamic Web Project  in Eclipse.
  • Add the project name as CustomTag.
  • Select Target runtime as Apache Tomcat 6.0.
  • Click on the finish button.
  • It will create CustomTag web project.




1. Tag Handler (UserTag.java)

  • Now we will create Tag Handler class.
  • Add the class name as UserTag in the package ctag.
  • Click on the finsih button.





  • The tag is defined in a handler class.
  • TagSupport is the base class used for simple tags.
  • It can be found in the javax.servlet.tagext package.
   
  • Now add the following code to the file UserTag.java. 
package ctag;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.*;
public class UserTag extends SimpleTagSupport {
public void doTag() throws JspException, IOException {
getJspContext().getOut().print("my custom tag");
getJspBody().invoke(null);
}
}

 

2. Tag Library Descriptor (tags.tld)

  • A tag library descriptor (TLD) file is an XML document that describes the library.
  • A TLD contains information about the library as a whole and about each tag contained in the library.
  • TLDs are used by a JSP container to validate the tags.
  • Now we will create tld file.
  • Tld file is basically xml file.
  • Rt. Click on the project.
  • Select New-->Other.



  • Select File.
  • Click on next button.



  • Add the file name as welcome.tld.
  • Click on the next button.



  • Now add the following content to the welcome.tld file.
welcome.tld
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.1</jsp-version>
<uri>mytag</uri>
<tag>
<name>utag</name>
<tag-class>ctag.UserTag</tag-class>
<body-content>scriptless</body-content>
<info>
This is a simple hello tag.
</info>
</tag>
</taglib>


 
3. Use tag in jsp (index.jsp)

  • Now we will use the tag that we have created.
  • In the WebContent will create one jsp file.
  • Save it as index.jsp.



  • Now add the following content to the index.jsp file.

index.jsp
<%@taglib uri="mytag" prefix="my"%>
<my:utag />

Running the application

  • Rt. click in the index.jsp code area.
  • Select Run As -->Run On Server.
  • Select the server tomcat 6.
  • It will deploy the application on the tomcat Server.
  • After deployment it will start the browser.

    

  • Now you can see the output.

Output

 

Download Zip Code

Type of Tags


Custom tags can be created of two types one which have body and other which have no
body. Tags can be categorized as:
 
1. Simple Tags (<mytags:myfirsttag/>)
2. Tags With Attributes (<mytags:hello name="Deepak"/>)
3. Tags with Bodies
<mytags:bodysingletag textCase="upper">
This is body.
</mytags:bodysingletag>
)
 

Simple Tags

A simple tag contains no body and no attributes:
 
<mytags:myfirsttag/>
 

Tags With Attributes

1. Tag Handler (Hello.java)

Define Getter/Setter for the attribute name of the tag.
 
package mytag;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class Hello extends TagSupport {
private String name=null;
public void setName(String value){
name = value;
}
public String getName(){
return(name);
}
public int doStartTag() throws JspException{
  try {
  JspWriter out = pageContext.getOut();
  out.println("Hello <b>" + name + "</b>");
  }
  catch (Exception ex) {
  System.out.println(ex.toString());
  }
  return SKIP_BODY;
  }
  public int doEndTag() throws JspException{
  return EVAL_PAGE;
  }
  }
Download Source
 
Tag Library Descriptor (tags.tld)
 
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<tag>
<name>hello</name>
<tagclass>mytag.Hello </tagclass>
<bodycontent>empty</bodycontent>
<attribute>
<name>name</name>
<required>true</required>
</attribute>
</tag>

 
Use tag in jsp (tagattribute.jsp)
  
<%taglib prefix="mytags" uri="/WEB-INF/tags.tld" %>
<html>
<body>
<h2>Tags With Attributes</h2>
<mytags:hello name="mohan"/>
</body>
</html>
Download Source
  Download Zip Code




Tags with Bodies

  • If the tag handler needs to interact with the body, the tag handler must implement BodyTag (or be derived from BodyTagSupport)
  •  If the body of the tag needs to be evaluated, the doStartTag method needs to return EVAL_BODY_INCLUDE.
  •  A tag handler for a tag with a body is implemented differently depending on whether the body needs to be evaluated once or multiple times.
  •  Single Evaluation: if the body needs to be evaluated once.
  •  Multiple Evaluation: if the body needs to be evaluated multiple times

Tag Handler (BodySingleTag.java)
  
package mytag;
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class BodySingleTag extends BodyTagSupport {
private String textCase;
public void setTextCase(String textCase) { this.textCase = textCase; }
public int doAfterBody() throws JspException {
try {
BodyContent bc = getBodyContent();
String body = bc.getString();
JspWriter out = bc.getEnclosingWriter();
if (body != null) {
  if ("upper".equalsIgnoreCase(textCase)) {
  out.print(body.toUpperCase());
  else {
  out.print(body.toLowerCase());
  }
  }
  catch (IOException ioe) {
  throw new JspException("Error: " + ioe.getMessage());
  }
  return SKIP_BODY;
  }
  }
Download Code
Tag Library Descriptor (tags.tld)
 
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.2</jspversion>

<tag>
<name>bodysingletag</name>
<tag-class>mytag.BodySingleTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>textCase</name>
<required>true</required>
</attribute>
</tag>
</taglib>

 
 Use tag in jsp (bodysingle.jsp)
 
<%taglib prefix="mytags" uri="/WEB-INF/tags.tld" %>
<html>
<body>
<h2>Body Single Custom Tag</h2>
<mytags:bodysingletag textCase="upper">
Body is evaluated once.
</mytags:bodysingletag>
</body>
</html>
Download Code
Download Zip

Output


 

Tag Handler (BodyMultipleTag.java)

Here is an example of a single evaluation where we extend the BodyTagSupport class. The
example tag accepts an integer as its attribute, and prints its body HTML as many times
as indicated in the JSP code
  
package mytag;
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class BodyMultipleTag extends BodyTagSupport{
private int counts = 0;
private BodyContent bodyContent;
public void setBodyContent(BodyContent bodyContent) {
this.bodyContent = bodyContent;
}
public void setCounts(int counts) {
this.counts = counts;
}
public int doStartTag() throws JspException {
  if (counts >0) {
  return EVAL_BODY_TAG;
  }else {
  return SKIP_BODY;
  }
  }
  public int doAfterBody() throws JspException {
  if (counts >1) {
  counts--;
  return EVAL_BODY_TAG;
  else {
  return SKIP_BODY;
  }
  }
  public int doEndTag() throws JspException {
    try {
    if(bodyContent != null) {
    bodyContent.writeOut(bodyContent.getEnclosingWriter());
    }
    catch(IOException e) {}
    return EVAL_PAGE;
    }
    }
  
Download Code
Tag Library Descriptor (tags.tld)
 
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.2</jspversion>

<tag>
<name>bodymultipletag</name>
<tag-class>mytag.BodyMultipleTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>counts</name>
<required>true</required>
</attribute>
</tag>
</taglib>

 bodymultiple.jsp
 
<%taglib prefix="mytags" uri="/WEB-INF/tags.tld" %>
<html>
<body>
<h2>Body Multiple Custom Tag</h2>
<mytags:bodymultipletag counts="3">
JaiswalTraining<br>
</mytags:bodymultipletag>
</body>
</html>
Download Code
Download Zip