Monday, 19 January 2015

Custom Tags in Jsp with example


       User-defined tags are known as custom tags.  It is very useful in JSP programming for the programmers to write their own custom components for their projects. These custom tags can be re-used in many places without modification of code. In the latest trend of web development, very few developers write their own custom tags, the reason is that many web frameworks like Struts, Spring, etc. provide more advanced custom tags pre-built with their framework. To understand the custom tag and how it works is very important for a programmer.

          In this tutorial we will see how to create a custom tag and use it in JSP.
There are two ways to create the custom tags in JSP as follows,
1)Tag handlers
2)Tag files

       Tag Handlers:
         To create a custom tag we need three things:
1) Tag handler class:  In this class we specify what our custom tag will do when it is used in a
                                     JSP  page.
2) TLD file:  Tag descriptor file where we will specify our tag name, tag handler class and tag
                                     attributes.
3) JSP page:    A JSP page where we will be using our custom tag.

Tag Handler class:

      Tag handlers are Java classes that implement the custom tag. A tag file is a source file containing JSP code  that is translated into a simple tag handler by the web container. Same as with JSPs and serlvets.  The following tag handler is used to respond to doTag() method and sends Column value from the database back to  JSP in which it is placed(Column Name and Table Name we are giving in JSP as required parameters of the custom tag). WEB-INF/classes/com/admail/customTags/DropDownBoxTag.java .

  package com.admail.customTags;
  import java.io.IOException;
  import java.sql.Connection;
  import java.sql.DriverManager;
  import java.sql.ResultSet;
  import javax.servlet.jsp.JspException;
  import javax.servlet.jsp.JspWriter;
  import javax.servlet.jsp.PageContext;
  import javax.servlet.jsp.tagext.SimpleTagSupport;
  import com.mysql.jdbc.PreparedStatement;

  public class DropDownBoxTag extends SimpleTagSupport{
         private String tableName;
         private String columnName;
         public String getTableName() {
                 return tableName;
         }
         public void setTableName(String tableName) {
                 this.tableName = tableName;
         }
         public String getColumnName() {
                 return columnName;
         }
         public void setColumnName(String columnName) {
                 this.columnName = columnName;
         }
         public void doTag() throws JspException, IOException {
                 Connection con = null;
                 PreparedStatement st = null;
                 ResultSet rs= null;
                 StringBuffer htmlContent = new StringBuffer();
                 try{
                        Class.forName("com.mysql.jdbc.Driver");
                        con = DriverManager.getConnection("jdbc:mysql://localhost/mail","root","nrk");
                        st = (PreparedStatement) con.prepareStatement("select "+columnName+" from "
                                                           +tableName+"  order by "+columnName);
                        rs = st.executeQuery();
                        htmlContent.append("<select name=");
                        htmlContent.append("'");
                        htmlContent.append("drop");
                        htmlContent.append("'");
                        htmlContent.append(">");
                        htmlContent.append("<option value='");
                        htmlContent.append("'");
                        htmlContent.append(">");
                        htmlContent.append("Select");
                        htmlContent.append("</option>");
                        while (rs.next()){
                                htmlContent.append("<option value='");
                                htmlContent.append(rs.getString(columnName));
                                htmlContent.append("'");
                                htmlContent.append(">");
                                htmlContent.append(rs.getString(columnName));
                                htmlContent.append("</option>");
                        }
                        htmlContent.append("</select>");
                        JspWriter writer = getJspContext().getOut();
                        writer.print(htmlContent.toString());
                }
                catch(Exception e){
                        e.printStackTrace();
                }
          }
   }

DropDownBoxTag class extends SimpleTagSupport, which is implementing SimpleTag interface.
SimpleTag interface contains the following other methods:

doTag()
getParent()
setParent(JspTag)
setJspBody(JspFragment)
getJspBody()
setJspContext(JspContext)
getJspContext()

We have used doTag(), which is invoked when Container encounters tag in JSP.

TLD File:

             Each custom tag implemented with a tag handler must be declared in a special xml file called tag library descriptor — (TLD). The TLD file maps custom tags to their corresponding simple  tag handler implementation classes. We can keep .tld file in your WEB-INF directory i.e WEB-INF/dropdown.tld.

<?xml version="1.0" encoding="UTF-8" ?>
<taglib>
      <tlib-version>1.1</tlib-version>
       <jsp-version>2.0</jsp-version>
       <info>Tag library for Drop Down Box</info>
       <tag>
              <name>options</name>
              <tag-class>com.customTags.DropDownBoxTag</tag-class>
               <body-content>empty</body-content>
               <attribute>
                       <name>tableName</name>
                       <required>true</required>
               </attribute>
               <attribute>
                      <name>columnName</name>
                      <required>true</required>
               </attribute>
     </tag>
  </taglib>

JSP Page:
       Above custom tag we can use in JSP as follows. In this JSP table name is states and column name is state_names. We are passing dynamically table and column names.

       <%@ taglib uri="/WEB-INF/custom.tld"  prefix="tag"%>
       <html>
      <head>
           <title>A sample custom tag</title>
      </head>
       <body>
               <tag:options tableName="states" columnName="state_names" />
      </body>
      </html>

                         Tag file:--
      In this custom tag,you don't need a tag library descriptor for your custom tags. Nor do you have to compile your tag handlers. Now, even those who don't understand Java can write custom tags.

To create a custom tag we need two things:
1. Writing and compiling a tag handler.
2.Defining the tag that is associated with the tag handler.

       Tag files simplify the process. First, tag files don't need to be compiled. They are compiled as they are invoked. Also, tag files allow tag extensions to be written using only JSP syntax. This means someone who does not know Java can also write tag extensions!

       Secondly, a tag element in a tag library descriptor describes the name to be used in a JSP page to reference the custom action. Using tag files, the name of a custom action is the same as the tag file representing the action. Therefore, you don't need a tag library descriptor at all.

         A tag file looks like a JSP page. It can have directives, scripts, EL expressions, and standard and custom tags. A tag file has the .tag or .tagx extension and can also include other files that contain a common resource. An include file for a tag file has a .tagf extension.

        To work, tag files must be placed in the WEB-INF/tags directory under your application directory or a subdirectory under it. Just like tag handlers, tag files can also be packaged.

      A number of implicit objects are available from inside of a tag file. You can access these objects from a script or an EL expression.  Implicit objects available in a tag file are as follows.

  Implicit Objects in Tag File:-

request - javax.servlet.http.HttpServletRequest
response - javax.servlet.http.HttpServletResponse
out - javax.servlet.jsp.JspWriter
session - javax.servlet.http.HttpSession
application - javax.servlet.ServletContext
config - javax.servlet.ServletConfig
jspContext - javax.servlet.jsp.JspContext

 Note that these implicit objects are similar to those available in a JSP page.

 Example of  TLD File:
    This example shows how to write  .tag file and how to use the tag file in JSP. The directory structure of the application is as follows.

Custom tag directory structure


                                                                                              
The below dateTag.tag looking similar to JSP page. The dateTag.tag file has a tag directive with two import attributes and some script. The output of this tag file is the current date in long format. To use this tag file as a tag extension, all you need to do is save it in the WEB-INF/tags directory of your application. The tag file name is important because it indicates the tag name. Therefore, for the tag file with the name dateTag.tag, the tag name will be dateTag.

   The above dateTag.tag is used in the DateTagEx.jsp .The DateTagEx.jsp is,

   <%@ taglib uri="/WEB-INF/tags"  prefix="tag"%>
      <html>
          <head>
             <title>A sample custom tag</title>
         </head>
              <body>
                     The current Date is : <tag:dateTag  />
             </body>
   </html>


Related Post:--
1) What are the Implicit Objects in JSP?
2) What is the difference between SendRedirect() and Forward().?

No comments:

Post a Comment