|
|||||
Web
Design & Development CS506
VU
Lesson
38
JSP
Custom Tags
To
begin with, let's review
our last code example of
lecture 36 i.e. Displaying
course outline. We
incorporated
JavaBeans to minimize the database
logic from the JSP. But
still, we have to write some
lines
of
java code inside java.jsp
& web.jsp. As discussed earlier,
JSPs are built for
presentation purpose only, so
all
the other code that involves
business and database logic
must be shifted else where
like we used
JavaBeans
for such purpose.
There
is also another problem attached to
it. Generally web page
designers which have enough
knowledge
to
work with HTML and some
scripting language, faced lot of
difficulties in writing some
simple lines of
java
code. To overcome these issues,
java provides us the mechanism of
custom tags.
Motivation
To
give you an inspiration,
first have a glance over the
code snippet we used in JSP
of the course outline
example
of last lecture. Of course, not
all code is given here; it's
just for your reference to
give you a hint.
<%
CourseDAO
courseDAO = new
CourseDAO();
..................
//
iterating over
ArrayList
for
(........................ ) {
........................
........................
//
displaying courseoutline
}
..................
%>
Can
we replace all the above code with one
single line? Yes, by using
custom tag we can write like
this:
<mytag:coursetag
pageName="java" />
By
only specifying the course/page
name, this tag will display
the course outline in tabular
format. Now,
you
must have realized how
significant changes custom
tags can bring
on.
What is
a Custom Tag?
In
simplistic terms, "a user
defined component that is used to
perform certain action".
This action
could
be as simple as displaying "hello
world" or it can be as complex as
displaying course
outline
of
selected course after
reading it form
database.
It
provides mechanism for encapsulating
complex functionality for
use in JSPs. Thus facilitates
the
non-java
coders.
We
already seen & used many
built in tags like:
-<
jsp:useBean ...... />
-<
jsp:include ...... />
-<
jsp:forward ...... /> etc.
Why
Build Custom Tag?
We
introduced action <jsp:useBean> and
JavaBeans to incorporate complex,
encapsulated
functionality
in a JSP.
However,
JavaBeans cannot manipulate JSP content
and Web page designers must have
some
knowledge
to use JavaBeans in a
page
With
Custom tags, it is possible for
web page designers to use
complex functionality
without
knowing
any java
Advantages of
using Custom Tags
Provides
cleaner separation of processing logic and
presentation, than JavaBeans.
Have
access to all JSP implicit
objects like out, request
etc.
Can
be customized by specifying
attributes.
Types
of Tags
Three
types of can be constructed. These
are:
284
Web
Design & Development CS506
VU
1
Simple
Tag
2
Tag
with Attribute
3
Tag
with Body
1.
Simple Tag
A
simple tag has the following
characteristics:
-Start
and End of tag -No body is
specified within tag -No
attributes -For
example
2. Tag
with Attributes
A tag
with attributes has the
following characteristics:
-Start
and End of tag
-Attributes
within tag
-No
body enclosed
-For
example
<
mytag:hello attribute
= "value" />
3. Tag
with Body
A tag
with body has the following
characteristics:
-Start
and End of tag
-May
be attributes
-Body
enclosed within tag
-For
example
<
mytag:hello optional_attributes ............
>
some
body
</
mytag:hello >
Building
Custom Tags
So
far, we have used many
built-in tags. Now the time
has come to build your
own one. Custom tags can
be
built
either by using JSP 1.2
specification or JSP 2.0
(latest) specification.
To
develop custom tags using
JSP 1.2 involves lot of
cumbersome (too difficult
for James Gossling
also☺).
However, JSP 2.0 brings
lots of goodies like
Simple
tag extensions to build custom
tags
Integrated
Expression Language (will be discussed in
coming lecture)
Also
provides an alternate mechanism for
building custom tags using
tag files (.tag)
Improved
XML syntax etc.
Steps
for Building Custom
Tags
The
following steps are used in
order to develop your own
custom tag. These
are:
1
Develop the Tag Handler
class
2
Write Tag library
Descriptor (.tld)
file
3
Deployment
1.
Develop the Tag Handler
class
Tag
Handler is also a java class
that is implicitly called
when the associated tag is encountered
in
the
JSP.
Must
implement SimpleTaginterface
Usually
extend from SimpleTagSupport
class that has already
implemented SimpleTag
interface.
For
example,
285
Web
Design & Development CS506
VU
public
class MyTagHandler extends
SimpelTagSupport {
...........................
...........................
}
doTag()
method
· By
default does nothing
· Need
to implement / override to code/write
functionality of tag
· Invoked
when the end element of the tag encountered.
JSP
implicit objects (e.g. out etc) are
available to tag handler class
through pageContextobject.
pageContextobject
can be obtained using
getJspContext() method.
For
example to get the reference of implicit
outobject, we write.
PageContext pc =
(PageContext) getJspContext();
JspWriter
out = pc.getOut();
2.
Write Tag Library Discriptor
(.tld) file
· It is a XML
based document.
· Specifies
information required by the JSP
container such as:
-Tag
library version
-JSP
version
-Tag
name
-Tag
Handler class name
-Attribute
names etc.
Note:
If
you are using any
IDE (like netBeans® 4.1, in
order to build custom tags,
the IDE will
write
.tldfile for you.
3.
Deployment
· Place
Tag Handler class in
myapp/WEB-INF/classes folder of web
application.
· Place
.tld file in myapp/WEB-INF/tldsfolder of
web application.
Note:
Any good IDE will also
perform this step on your
behalf Use
taglib directive in JSP to
refer
to the tag
library. For example
<%@
taglib uri="TLD file name"
prefix="mytag" %>
The
next step is to call the tag by
its name as defined in TLD.
For example, if tag name is
hello then we
write:
<
mytag:hello /> where mytag is the name
of prefix specified in
taglibdirective.
What
actually happened behind the
scenes? Container calls the doTag()
method of appropriate tag handler
class.
After that, Tag Handler
will write the appropriate
response back to the page.
Example
Code: Building simple tag that displays
"Hello World"
Enough
we have talked about what
are custom tags, their
types. Now, it is a time to build a
custom tag that
displays
"Hello World".
Approach
· Extend
Tag Handler class from
SimpleTagSupport class and override
doTag() method
· Build
TLD file
· Deploy
Note:
As
mentioned earlier, if you
are using any IDE
(like netBeans® 4.1), the last two
steps will be
performed
by the IDE.
WelcomeTagHandler.java
286
Web
Design & Development CS506
VU
package
vu;
//
importing required
packages
import
javax.servlet.jsp.*;
import
javax.servlet.jsp.tagext.*;
//
overriding doTag() method
public
void doTag() throws JspException
{
//
obtaining the reference of out implicit
object
PageContext
pageContext = (PageContext)getJspContext();JspWriter
out = pageContext.getOut();
try
{
out.println("
Hello World ");
}
catch (java.io.IOException ex)
{throw new
JspException(ex.getMessage());}
} // end
doTag() method
} end
WelcomeTagHandler class
customtags.tld
If
using IDE, this file
will be written automatically. In
this file you specify the
tag name along with
Tag
Handler
class.
<?xml
version="1.0"
encoding="UTF-8"?>
<taglib
version="2.0"
xmlns="http://java.sun.com/xml/ns/j2ee"xmlns:xsi="http://www.w3.org/2001/XMLSch
ema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
web-
jsptaglibrary_2_0.xsd">
<tlib-version>1.0</tlib-version>
<short-name>mytag</short-name>
<!--the
value of uri will be used in
JSP to refer to this tld
-->
<uri>/WEB-INF/tlds/customtags</uri>
<!--
Specifying the tag name and tag class.
Also mentioning thatthis tag
has no body
-->
<tag>
<name>welcome</name>
<tag-class>vu.WelcomeTagHandler</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
<%--
using
taglib directive, specifying the
tld file name as well
asprefix. Note that you
you use any value
for
the
prefix attribtute
--%>
<%@taglib
uri="/WEB-INF/tlds/customtags.tld" prefix="mytag"
%>
<html>
<body>
<h2>A
Simple Tag
Example</h2>
<h3>
<%-- calling welcome tag with the
help of prefix --%><mytag:welcome
/>
</h3>
</body></html>
Building
tags with attributes
If
you want to build a tag that
can also take attributes,
for example
<mytag:hello
attribute="value"
/>
To
handle attributes, you need
to add
287
Web
Design & Development CS506
VU
·
Instance
variables and
·
Corresponding
setter methods
Behind
the scenes, container will
call these setter methods
implicitly and pass the value of the
custom tag
attribute
as an argument.
In
this example, we will modify
our course outline example
to incorporate tags. Based on
attribute value,
the tag
will display the respective course
outline in tabular
format.
Approach
· Extend
Tag Handler class from
SimpleTagSupport class
-Add
instance variable of type
String
-Write
setter method for this
attribute
-Override
doTag() method
·
Build
TLD file
·
Deploy
CourseOutlineBean.java
This
is the same file used in the last
example
package
vubean;
import
java.io.*;
public
class CourseOutlineBean implements
Serializable{
private
int sessionNo;
private
String topic;
private
String assignment;
// no argument
constructor
public
CourseOutlineBean() {
sessionNo
= 0;
topic
= "";
assignment
= "";
}
//
setters
public
void setSessionNo(int s){
sessionNo
= s;
}
public
void setTopic(String
t){
topic
= t;
}
public
void setAssignment(String
a){
assignment
= a;
}
//
getterspublic int getSessionNo( ){return
sessionNo;}
public
String getTopic( ){return
topic;}
public
String getAssignment( ){return
assignment;}
} //
end class
CourseDAO.java
No
changes are made to this
file too.
package
vu;
288
Web
Design & Development CS506
VU
import
java.io.*;import java.sql.*;import
java.util.*;
public
class CourseDAO implements
Serializable{
private
Connection con;
public
CourseDAO() {
establishConnection();
}
//**********
establishConnection method ********************// method
used to make
connection
with
databaseprivate void establishConnection(){
try{//
establishing
conectionClass.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String
conUrl = "jdbc:odbc:CourseDSN";con
=
DriverManager.getConnection(conUrl);
}catch(Exception
ex){
System.out.println(ex);
}
}
ArrayList
courseList = new ArrayList();
try{
String
sql = " SELECT sessionNo,
topic, assignment " +" FROM
Course, SessionDetail" +"
WHERE
courseName = ? " + " AND Course.courseId =
SessionDetail.courseID
";
PreparedStatement
pStmt = con.prepareStatement(sql);pStmt.setString(1,
cName);
ResultSet
rs = pStmt.executeQuery();
int
sNo;
String
topic;
String
assignment;
while
( rs.next() ) {
sNo =
rs.getInt("sessionNo");topic =
rs.getString("topic");assignment
= rs.getString("assignment");
if
(assignment == null){assignment =
"";}
//
creating a CourseOutlineBean
objectCourseOutlineBean cBean =
new
CourseOutlineBean();
cBean.setSessionNo(sNo);cBean.setTopic(topic);cBean
.setAssignment(assignment);
//
adding a bean to
arraylist
courseList.add(cBean);
}
}catch(Exception
ex){
System.out.println(ex);
}
finally {
// to
close connection
releaseResources();
}
//
returning ArrayList
object
return
courseList;
} // end
retrieveCourseOutline
289
Web
Design & Development CS506
VU
try{
if(con
!= null){
con.close();
}
}catch(Exception
ex){
System.out.println();
}
} //
end releaseResources
}//
end CourseDAO
MyTagHandler.java
The
tag handler class uses
JavaBeans (CourseOutlineBean.java &
CourseDAO.java), and includes the
logic
of
displaying course outline in
tabular format.
package
vutag;
//
importing package that contains the
JavaBeansimport vubean.*;
import
javax.servlet.jsp.tagext.*;import
javax.servlet.jsp.*;import
java.util.*;
public
class MyTagHandler extends
SimpleTagSupport {
/**
*
Declaration of pageName property.
*/
private
String pageName;
public
void doTag() throws JspException
{
CourseDAO
courseDAO = new
CourseDAO();
ArrayList
courseList =
courseDAO.retrieveCourseList(pageName);
// to
display course outline in
tabular form, this method
is// used define
below
display(courseList);
}
/**
*
Setter for the pageName
attribute.
*/
public
void setPageName(java.lang.String value)
{this.pageName = value;
}
/**
*
display method used to print
courseoutline in tabular
form
*/private
void display(ArrayList courseList)throws
JspException{
PageContext
pc = (PageContext)getJspContext();
JspWriter
out = pc.getOut();
try{
//
displaying table
headers
out.print("<TABLE
BORDER=1 >");
out.print("<TR>");
out.print("<TH>
Session No </TH>");
out.print("<TH>
Topic </TH>");
out.print("<TH>
Assignment </TH>");
out.print("</TR>");
//
loop to iterate over
courseList
for
(int i=0; i<courseList.size();
i++){
CourseOutlineBean
courseBean =
(CourseOutlineBean)courseList.get(i);
290
Web
Design & Development CS506
VU
//
displaying one row
out.print("<TR>");
out.print("<TD>"
+ courseBean.getSessionNo() +
"</TD>");
out.print("<TD>"
+ courseBean.getTopic() +
"</TD>");
out.print("<TD>"
+ courseBean.getAssignment() +
"</TD>");
out.print("</TR>");
}
out.print("</TABLE>");
}catch(java.io.IOException
ex){throw new
JspException(ex.getMessage());}}
} //
end clas
MyTagHandler.java
<?xml
version="1.0"
encoding="UTF-8"?>
<taglib
version="2.0"
xmlns="http://java.sun.com/xml/ns/j2ee"xmlns:xsi="http://www.w3.org/2001/XMLSch
ema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
web-
jsptaglibrary_2_0.xsd">
<tlib-version>1.0</tlib-version>
<short-name>mytaglibrary</short-name>
<!--the
value of uri will be used in
JSP to refer to this tld
-->
<uri>/WEB-INF/tlds/mytaglibrary</uri>
<!--
Specifying the tag name and tag class.
Also mentioning thatthis tag
has no body
-->
<tag>
<name>coursetag</name>
<tag-class>vutag.MyTagHandler</tag-class>
<body-content>empty</body-content>
<!--
Specifying
the attribute name and its
type
-->
<attribute>
<name>pageName</name>
<type>java.lang.String</type>
</attribute>
</tag>
</taglib>
index.jsp
This
page is used to display the
course options to the user in the
radio button form.
<html>
<body>
<h2>Select
the page you want to
visit</h2>
<form
name="myForm" action="controller.jsp"
>
<h3>
<input type="radio" name =
"page" value="web"/>Web Design &
Develoment
</h3>
<br>
<h3>
<input type="radio" name =
"page" value="java"/>Java
291
Web
Design & Development CS506
VU
</h3>
<br>
<input
type="submit" value="Submit" />
</form>
</body>
</html>
controller.jsp
Based
upon the selection made by the user,
this page will redirect the
user to respective pages. Those
are
web.jspand
java.jsp
<html>
<body>
<!--
scriptlet -->
<%
String
pageName = request.getParameter("page");
if
(pageName.equals("web")) {
response.sendRedirect("web.jsp");
}
else if (pageName.equals("java") )
{
response.sendRedirect("java.jsp");}%>
</body>
</html>
java.jsp
<%--
using taglib directive,
specifying the tld file and
prefix --%>
<%@taglib
uri="/WEB-INF/tlds/mytaglibrary.tld"
prefix="mytag"%>
<html>
<body>
<center>
<h2> Welcome to Java Learning
Center </h2><h3> Course
Outline</h3>
<%--calling
coursetag and specifying
java as attribute
value
--%>
<mytag:coursetag
pageName="java" />
</center>
</body>
</html>
web.jsp
<%--
using taglib directive,
specifying the tld file and
prefix --%>
<%@taglib
uri="/WEB-INF/tlds/mytaglibrary.tld"
prefix="mytag"%>
<html>
<body>
<center>
<h2>
Welcome to Java Learning Center
</h2><h3> Course
Outline</h3>
<%--calling
coursetag and specifying
java as attribute
value
--%>
<mytag:coursetag
pageName="java" />
</center>
</body>
</html>
References
·
Java
A Lab Course by Umair
Javed.
·
Core Servlets
and JavaServer Pages by Marty
Hall
292
Table of Contents:
|
|||||