Tuesday 27 August 2013

JSP & CUSTOM TAG LIBRARY


JSP Implicit Objects :

  1. Request
  2. Response
  3. Session
  4. Application
  5. Config
  6. Page Context
  7. Out
  8. Page
  9. Exception


Custom Tag Library :

Step 1: Write a TagHandler Class by implements TagHandler or extends TagSupport
-> Write Setter & getter for attributes which are going to use in TLD file.
Step 2: Write tag Descriptor File called TLD and keep it in WEB-INF Directory.
Step 3: Now write a jsp page and use the custom taglib.

Example:

CustomTagClass.java 

Package com.customtagexaples.CustomTagClass
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
public class CustomTagClass extends TagSupport {
    private String input;
    private int start;
    private int end;
     
    @Override
    public int doStartTag() throws JspException {
         
        try {
            //Get the writer object for output.
            JspWriter out = pageContext.getOut();
            //Perform substr operation on string.
            out.println(input.substring(start, end));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return SKIP_BODY;
    }
    public String getInput() {
        return input;
    }
    public void setInput(String input) {
        this.input = input;
    }
    public int getStart() {
        return start;
    }
    public void setStart(int start) {
        this.start = start;
    }
    public int getEnd() {
        return end;
    }
    public void setEnd(int end) {
        this.end = end;
    }
}
CustomTagHandlerTLD.tld 


<?xml version="1.0" encoding="UTF-8"?>
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>CustTag</shortname>
<info>Sample taglib for Custom tag operation</info>

<tag>
    <name>CustTagExample</name>
    <tagclass>com.customtagexaples.CustomTagClass</tagclass>
    <info>CustTagExample function.</info>
    <attribute>
      <name>input</name>
      <required>true</required>
    </attribute>
    <attribute>
      <name>start</name>
      <required>true</required>
    </attribute>
    <attribute>
      <name>end</name>
      <required>true</required>
    </attribute>
</tag>
</taglib
CustomeTagExample.jsp
<%@taglib prefix="test" uri="/WEB-INF/SubstrDescriptor.tld"%>
<html>
<head>
    <title>JSP Custom Taglib example: Substr function</title>
</head>
<body>
    SUBSTR(GOODMORNING, 1, 6) is :
    <font color="blue">
    <test:substring input="GOODMORNING" start="1" end="6"/>
    </font>
</body>
</html>
OutPut: 

SUBSTR(GOODMORNING, 1, 6) is: OODMO


No comments:

Post a Comment

SpringBoot

SpringBoot SpringBoot Application :  Pros & Cons :  SpringBoot Application creation using spring.io :  SpringBoot Application Annotation...