Tuesday, December 21, 2010

A Java Custom Tag: Displaying running Time on a web page.

In this Post we shall develop a Java Custom Tag to display running time on a Web Page. To display time we shall need to use JavaScript. I shall then package this up as a Custom Tag. We shall use Apache Tomcat as the Web Server. However, the process is completely general.


   

Here is the required JavaScript:
Timer.html
<script type='text/javascript'>
window.setInterval(function ()
{
var dd=document.getElementById('d1');
var d=new Date();
dd.innerHTML= d;
},1000);
</script>
<div id='d1'></div>


the window.setInterval call will call the function after every 1000 milliseconds, i,e after one second. This will then update the inner HTML of the div.


Now, to develop a Custom Tag.


To develop a Custom Tag we need to develop a class which extends SimpleTagSupport and implement the doTag method.Place this class in a package inside the WEB-INF/classes directory.


Next we need to create a TLD file and place it anywhere inside the WEB-INF directory. This TLD needs to be referred in the taglib uri expression in the JSP page.
To, start place the jsp-api.jar file on the class path

Create a Directory CustomTags inside webapps.
Create CustomTags\WEB-INF

Create CustomTags\WEB-INF\classes,
Create CustomTags\WEB-INF\classes\tagpackage.


I have had to create a new method to give a new name to the div to avoid any clash with any existing controls. Therefore, I have concatenated the current milliseconds. That is also why I have added the sleep for 2 milliseconds because it will give a new ID to the div if more than one are placed in the same page.

The Tag Handler Class
time.java
package tagpackage;
import javax.servlet.jsp.*;
import java.io.*;
import javax.servlet.jsp.tagext.*;
public class time extends SimpleTagSupport
{
public void doTag()throws JspException,IOException
{
try
{
java.util.Date d=new java.util.Date();
Thread.sleep(2);
long millis=d.getTime();
String name="d" + millis;
JspWriter out=getJspContext().getOut();
out.print("<script type='text/javascript'>\n");
out.print("window.setInterval(function ()\n");
out.print("{\n");
out.print("var dd=document.getElementById('" + name + "');\n");
out.print("var d=new Date();\n");
out.print("dd.innerHTML= d;\n");
out.print("},1000);\n");
out.print("</script>\n");
out.print("<div id='" + name + "'></div>");
}
catch(Exception ex)
{

}
}
}





The TLD File
MyTags.tld
<?xml version="1.0" encoding="UTF-8" ?>
<taglib version="2.0" >
<tlib-version>1.0</tlib-version>
<tag>
<name>TimeTag</name>
<tag-class>tagpackage.time</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>



TimeTag.jsp

<%@ taglib uri="/WEB-INF/MyTags.tld" prefix="test" %>
<test:TimeTag/>



No comments:

Post a Comment