Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
14.2 Defining a Basic Tag
315
The Tag Handler Class
Tags that either have no body or that merely include the body verbatim
should extend the 
TagSupport
 class. This is a built in class in the
javax.servlet.jsp.tagext
 package that implements the 
Tag
 interface
and contains much of the standard functionality basic tags need. Because of
other classes you will use, your tag should normally import classes in the
javax.servlet.jsp
 and 
j
ava.io
 packages as well. So, most tag implementa 
tions contain the following 
import
 statements after the package declaration:
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
I recommend that you download an example from 
http://www.coreserv 
lets.com/
 and use it as the starting point for your own implementations.
For a tag without attributes or body, all you need to do is override the
doStartTag
 method, which defines code that gets called at request time
where the element's start tag is found. To generate output, the method
should obtain the 
JspWriter
 (the specialized 
PrintWriter
 available in JSP
pages through use of the predefined 
out
 variable) from the 
pageContext
field by means of 
getOut
. In addition to the 
getOut
 method, the 
pageCon 
text
 field (of type 
PageContext
) has methods for obtaining other data struc 
tures associated with the request. The most important ones are 
getRequest
,
getResponse
, 
getServletContext
, and 
getSession
.
Since the 
print
 method of 
JspWriter
 throws 
IOException
, the 
print
statements should be inside a 
try
/
catch
 block. To report other types of
errors to the client, you can declare that your 
doStartTag
 method throws a
JspException
 and then throw one when the error occurs.
If your tag does not have a body, your 
doStartTag
 should return the
SKIP_BODY
 constant. This instructs the system to ignore any content between
the tag's start and end tags. As we will see in Section 14.5 (Optionally Includ 
ing the Tag Body), 
SKIP_BODY
 is sometimes useful even when there is a tag
body, but the simple tag we're developing here will be used as a stand alone
tag (
 />
) and thus does not have body content.
Listing 14.4 shows a tag implementation that uses this approach to gener 
ate a random 50 digit prime through use of the 
Primes
 class developed in
Chapter 7 (Generating the Server Response: HTTP Response Headers)  
see Listing 7.4. 
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.






footer




 

 

 

 

 Home | About Us | Network | Services | Support | FAQ | Control Panel | Order Online | Sitemap | Contact

jsp web hosting

 

Our partners: PHP: Hypertext Preprocessor Best Web Hosting Java Web Hosting Jsp Web Hosting Cheapest Web Hosting

Visionwebhosting.net Business web hosting division of Web Design Plus. All rights reserved