Sunday, September 11, 2011

Java Tag Libraries - An Introduction.

Java Tag libraries allow developers seperate presentation layer from design/code layer in your Java Server Pages. You can have a professional designer design the look and feel or the layout of your web page and you can have an expert Java programmer create the necessary class libraries for the designer to call.

In order to create tag libaries, you will need to
- download and install servlet-2.3.jar or compatible version of servlet library within your lib folder of your Java installation.

The javax.servlet.jsp package ships with the install package of Tomcat.
You can download and install tomcat from
http://apache.cyberuse.com/tomcat/tomcat-7/v7.0.21/bin/apache-tomcat-7.0.21-windows-x86.zip

Note:- To learn a bit more about servlet package, refer to this documentation link
http://download.oracle.com/javaee/6/api/javax/servlet/package-summary.html

This links offers a history about servlets
http://weblogs.java.net/blog/driscoll/archive/2005/12/servlet_history_1.html

The logic of tag library works as follows
1. You have a JSP page that is requested by a client browser. Example :- The user enters in their browser http://server:8080/webapps/begjsp-ch02/currentTime.jsp.

2. The JSP page contains custom tags that basically executes the code associated with the custom tag in the background and send the output to JSP Runtime to send as output to the client requesting the currentTime.jsp page.

3. In order for the JSP page to execute code associated with the custom tag in the jsp page, JSP page should reference a TLD TLD (Tag Library Descriptor) file which maintains the mapping of custom tags used within the JSP to referenced tag-classes that have the java code.

Now lets get into the details....
The sample JSP file would appear as follows

<%@taglib prefix="example" uri="WEB-INF/tlds/exampleTags.tld" %>
<html>
<head> </head>
<body>
Welcome to my page. the current time is <example:time format="dd/MM/yy" evalPage="true"/>
<br>
<%
String [] strings = {"apples", "oranges", "bananas", "pineapples", "plums"};
pageContext.setAttribute("fruits", strings);
%>
Looping through fruit basket
<example:iterate>
The fruit is :
</example:iterate>

<example:foo>
<example:test/>
</example:foo>

<example:bodymod howMany="5"> Fruit name is:
</example:bodymod>

<p>


</body>

</html>

In the JSP example above we can see prefix="example" uri="WEB-INF/tlds/exampleTags.tld" in the first link of the sample above. In this example we will be referencing the tag