Jsp Custom Tag Simplifier Version

  • April 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Jsp Custom Tag Simplifier Version as PDF for free.

More details

  • Words: 2,291
  • Pages: 9
Overview In this tutorial we will learn what are custom JSP tags and how to build your first JSP tag. This tutorial assumes no prior knowledge about JSP tags. What are JSP tags? Well, if you know HTML, XML etc then you know what are tags. In any tag based language ( e.g. HTML ) anything between '<' and '>' is a tag e.g. is a title tag. These HTML tags are used on the client side in the browser to format the display of data on the user screen. Likewise in JSP we have tags between '<' and '>' and you can do just about anything you can think of on the server-side with them e.g. <star:firsttag />. One distinction between HTML and JSP tags is that all JSP tags obey XML tag rules. Meaning there by, all starting tags must have an end tag e.g. <star:firsttag> </star:firsttag>. If there is no end tag, then you should put '/' before the > tag e.g. <star:firsttag />. One other thing to notice is that all JSP tags have a prefix e.g. 'star' in <star:firsttag /> tag. Like HTML and XML tags, JSP tags can have attributes e.g. <star:firsttag attrib1="value1" attrib2="value2" /> has two attributes with two values. Why build and use JSP tags? Following are some of the uses which to mind : •<br /> <br /> • • • •<br /> <br /> Tags allow separation of Java ( server-side ) and HTML ( client-side ) code. Very important when you are building big projects and have separate people for client and server-side development. Tags allow easy reuse of Java code. You can build and pack a custom tag library with useful functions and provide it to the end-user. Due to their ease of use tags can be used by non-Java programmers e.g. HTML developers. Tags are easier to maintain. You don't have to edit every JSP page when you want to make a change, just change the JSP tag and change will be manifested by all the JSP pages.<br /> <br /> These were only the few important uses which come to mind immediately. Only once you learn how to build JSP tags, you'll realize how important JSP tags can be. Is building JSP tags difficult? Contrary to what you might be thinking, building JSP tags is as easy as building a normal Java class file. All we have to do is to make a Java class, then either implement one of the interfaces directly ( this is what we will do in this tutorial ) or extend one of the pre-made Java classes and override the method/s we need. As simple as that. Then you will have to build a simple text Tag Library Descriptor ( .TLD ) file in which you pack the information of one or all of your tags and make it available to the application server.<br /> <br /> Following are the topics we cover in this tutorial : • • • • •<br /> <br /> Overview ( this page ) Java class which implements Tag interface Tag Library Descriptor JSP page which calls the Tag Summary<br /> <br /> FirstTag.java Java Class File Create a new .java source file and save it as 'FirstTag.java' in the /WEBINF/classes/com/stardeveloper/tag/test/ folder of your web application. Now copy and paste the following code in it : package com.stardeveloper.tag.test; import java.io.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class FirstTag implements Tag, Serializable { private PageContext pc = null; private Tag parent = null; private String name = null; public void setPageContext(PageContext p) { pc = p; } public void setParent(Tag t) { parent = t; } public Tag getParent() { return parent; } public void setName(String s) { name = s; } public String getName() { return name; } public int doStartTag() throws JspException { try { if(name != null) { pc.getOut().write("Hello " + name + "!"); } else { pc.getOut().write("You didn't enter your name"); pc.getOut().write(", what are you afraid of ?"); }<br /> <br /> }<br /> <br /> } catch(IOException e) { throw new JspTagException("An IOException occurred."); } return SKIP_BODY;<br /> <br /> public int doEndTag() throws JspException { return EVAL_PAGE; } public void release() { pc = null; parent = null; name = null; } }<br /> <br /> Now compile this class. FirstTag.class file will be created.<br /> <br /> Explanation First line is the package statement, for our FirstTag class, we put it in the com.stardeveloper.tag.test package. package com.stardeveloper.tag.test;<br /> <br /> Then we import the classes we will be using. For FirstTag class, we import three packages. import java.io.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*;<br /> <br /> Explanation of FirstTag Class Code Then comes our FirstTag class declaration. Notice that we implement two interfaces; Serializable and Tag. We implement method-less interface Serializable so that our FirstTag class can be saved to the disk or serialized over the network. Serialization is not a requirement for building JSP tag classes. The next interface ( the important one ) which FirstTag class implements is the Tag interface. Like I said on the first page, our JSP tag class will have to implement one of the two interfaces, the two interfaces that I talked about are : • •<br /> <br /> Tag BodyTag<br /> <br /> These interfaces can be found in javax.servlet.jsp.tagext package. Tag is a simpler interface with about six methods to implement while BodyTag extends Tag interface to add three more methods and lot more features. Since we are building a simple JSP tag we will be implementing Tag interface.<br /> <br /> There are two classes provided in the javax.servlet.jsp.tagext package which provide default implementation for the above two interfaces : • •<br /> <br /> TagSupport BodyTagSupport<br /> <br /> Had we wanted we could have extended one of these classes and overridden the methods we needed. But I thought we should implement the Tag interface directly in this tutorial because it will aid in your learning about how it's different methods are used. public class FirstTag implements Tag, Serializable {<br /> <br /> The six methods which Tag interface provides and which we have to implement are : 1. 2. 3. 4. 5. 6.<br /> <br /> setPageContext(PageContext pc) setParent(Tag parent) getParent() doStartTag() doEndTag() release()<br /> <br /> Above six methods are a must. Now if we have attributes in our tag, like we have in this case i.e. name, then we have to add getter and setter methods for that attribute as well like is the case with JavaBean properties : 7. setName(String s) 8. getName() In our FirstTag class, we will be using three private variables. Two for saving reference to PageContext and Tag objects which are provided to us by setPageContext() and setParent() methods. And one for "name" attribute which is of type String. private PageContext pc = null; private Tag parent = null; private String name = null;<br /> <br /> Explanation of FirstTag Class Code In the setPageContext() method we save the reference to PageContext object in the private variable. public void setPageContext(PageContext p) { pc = p; }<br /> <br /> In setParent() method we save the reference to parent Tag object in the private variable. public void setParent(Tag t) { parent = t;<br /> <br /> }<br /> <br /> Likewise we code a getParent() method. public Tag getParent() { return parent; }<br /> <br /> Getter and setter methods for "name" attribute. public void setName(String s) { name = s; } public String getName() { return name; }<br /> <br /> doStartMethod() will be called with the start of the tag. In this method we use PageContext object to write value of "name" attribute back to the user. If the user has not entered his/her name in the "name" attribute of the tag then display a different message. We return SKIP_BODY from doStartTag() method as there is no body content in this tag. SKIP_BODY along with three other static variables is provided by the Tag interface. public int doStartTag() throws JspException { try { if(name != null) { pc.getOut().write("Hello " + name + "!"); } else { pc.getOut().write("You didn't enter your name"); pc.getOut().write(", what are you afraid of ?"); } } catch(IOException e) { throw new JspTagException("An IOException occurred."); } return SKIP_BODY; }<br /> <br /> doEndTag() is called when end of the tag is reached. It returns EVAL_PAGE so that rest of the page is read by the server. public int doEndTag() throws JspException { return EVAL_PAGE; }<br /> <br /> Lastly, we code the release() method. This method is called by the JSP page when all the methods of the tag class have been called and it is time to free resources. In this method you<br /> <br /> should free the resources you may have accumulated during the execution of other methods of the class.<br /> <br /> }<br /> <br /> public void release() { pc = null; parent = null; name = null; }<br /> <br /> Tag Library Descriptor A Tag Library Descriptor ( or simply TLD ) file is a simple XML file which provides details about your JSP tag/s. Create a new DemoTags.tld file in the /WEB-INF/tlds folder. Copy and paste the following text in it : <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> <taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <shortname>DemoTags</shortname> <uri>http://www.stardeveloper.com</uri> <info>Demo Tags Library</info> <tag><br /> <br /> <name>firsttag</name> <tagclass>com.stardeveloper.tag.test.FirstTag</tagclass> <bodycontent>empty</bodycontent> <info>Your first JSP Tag</info> <attribute rel="nofollow"> <name>name</name> <required>false</required> </attribute><br /> <br /> </tag> </taglib><br /> <br /> Explanation Everything is packed between <taglib> and </taglib> tags. First five sub-tags under the <taglib> tag are general tags for providing info about the tag library as a whole. They are not specific to any tag. <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> <taglib><br /> <br /> tlibversion tag tells about the current version of tag library. Since this is the first time we built this demo tag library, I put 1.0 in it. <tlibversion>1.0</tlibversion><br /> <br /> jspversion tells the application server what version of JSP this tag library uses. There are currently three versions of JSP, 1.0, 1.1 and future version 1.2. Our JSP tag FirstTag uses JSP version 1.1. <jspversion>1.1</jspversion><br /> <br /> A simple short name for the tag library. <shortname>DemoTags</shortname><br /> <br /> uri tag doesn't do much job in the current version of JSP. <uri>http://www.stardeveloper.com</uri><br /> <br /> A short text about the use of this tag library. <info>Demo Tags Library</info><br /> <br /> Now comes individual tag description between the <tag> and </tag> tag. <tag> <name>firsttag</name> <tagclass>com.stardeveloper.tag.test.FirstTag</tagclass> <bodycontent>empty</bodycontent> <info>Your first JSP Tag</info><br /> <br /> </tag><br /> <br /> <attribute rel="nofollow"> <name>name</name> <required>false</required> </attribute><br /> <br /> name is the short name you will be using in the JSP page after the prefix e.g. firsttag in the <star:firsttag /> tag. tagclass should contain the complete path to the JSP tag class. bodycontent should contain one of the three values; tagdependent, JSP and empty. Since there is body content in our tag so we select empty. Optional info tag.<br /> <br /> Then attribute tag describes each attribute separately. name is the name of the attribute, in our case it is "name". required can be true or false. We chose false so this tag can be used without entering value for the "name" attribute. We have finished building the FirstTag.class and DemoTags.tld files. Let's now build the JSP page which calls this tag. FirstTag.jsp JSP page Create a new JSP page under the folder where you can run JSP pages. For this demo, I'll assume /web/jsp folder. Save this .jsp page as FirstTag.jsp and copy / paste the following code in it : <html> <head><br /> <br /> </head> <body><br /> <br /> <title>Your first JSP tag : FirstTag <style> p, b { font-family:Tahoma,Sans-Serif; font-size:10pt; } b { font-weight:bold; }

<em>Your first JSP tag : FirstTag

<%@ taglib uri="/WEB-INF/tlds/DemoTags.tld" prefix="star" %>

Name entered : <star:firsttag name="Faisal Khan" />

No name entered : <star:firsttag />



Explanation We use the taglib directive to tell the application server we will be using a JSP tag in our JSP page. There are two attributes to taglib directive; uri and prefix. We set the uri attribute to the local address of DemoTags.tld TLD file. prefix attribute asks about the prefix we are going to use for this tag library, I chose "star". <%@ taglib uri="/WEB-INF/tlds/DemoTags.tld" prefix="star" %>

Then we use the tag twice in the JSP page, first time we enter our name in the name attribute for the tag. Second time we don't enter anything in the name attribute.

Name entered : <star:firsttag name="Faisal Khan" />

No name entered : <star:firsttag />



Ok we are done with FirstTag.jsp JSP page. Now run using a URL like http://localhost:8080/web/jsp/FirstTag.jsp . To see the online demo click here.

You will notice that the tag gives different response depending on value of the "name" attribute.

Summary We learned that JSP tags are a powerful way to re-use code. To create a custom JSP tag, you should first build a Java class which should either implement Tag or BodyTag interfaces present in the javax.servlet.jsp.tagext package or extend TagSupport or BodyTagSupport classes present in the same package. In this tutorial we implemented the Tag interface directly and also added an attribute "name" for our tag. To use attributes in your tags, you should provide a private variable with the same name as that of the attribute in your Java class, and then provide getter and setter methods for all of the attributes. The order with which JSP page calls the different of Tag interface is as follows : • • • • • • •

setPageContext() setParent() setAttribute1(value1) setAttribute2(value2) doStartTag() doEndTag() release()

You should release any resources you may have accumulated in your Java class file in the release() method of the Tag interface. We also learned to package one or more tags together, we make use of Tag Library Descriptor ( .TLD ) file. A .TLD file contains descriptions for one or more tags along with their attributes. In the end we built the FirstTag.jsp JSP page which called the firsttag. To call a custom built JSP tag in your JSP pages, you should make use of taglib directive and set it's uri attribute to the local address of this tag's .TLD file. And set the prefix attribute for taglib directive to any name you like. Well this is it for this time. Hope you liked the tutorial and learned how to create JSP tags.

Related Documents