Sie sind auf Seite 1von 23

Designing JSP Custom Tag Libraries

by Sue Spielman
04/19/2001

In this article you'll learn

• what a custom tag library is,


• why you want to use a custom tag library,
• the composition of a tag library, and
• how to build and use a complete library.

What a Custom Tag Library Is

If you've ever had the opportunity to build a web application using Java technology,
chances are you have used Java Server Pages (JSP) for content display. JSP is the
technology that helps separate the front end presentation from the middle and backend
tiers. The custom tag library is a powerful feature of JSP v1.1 that aids in that separation.
This technology is valuable to anyone who is building production-quality web applications,
and it is very applicable in today's market.

Custom tag libraries allow the Java programmer to write code that provides data access
and other services, and they make those features available to the JSP author in a simple to
use XML-like fashion. An action in a web application -- for example, gaining database
access -- can be customized by using a custom tag in a JSP page. The JSP author doesn't
have to understand the underlying detail to complete the action. In short, a tag library is a
collection of custom actions presented as tags.

Custom tags have many features that make them attractive to use from any JSP. Custom
tags can

• be customized via attributes passed from the calling page, either staticly or
determined at runtime;
• have access to all the objects available to JSP pages including request, response,
in and out;
• modify the response generated by the calling page;
• communicate with each other; you can create and initialize a JavaBeans
component, create a variable that refers to that bean in one tag, and then use the
bean in another tag;
• be nested within one another, allowing for complex interactions within a JSP page;
and
• encapsulate both simple and complex behaviors in an easy to use syntax and
greatly simplify the readability of JSP pages.

Any of these points is reason enough to consider using a tag library.

Let's look at what makes up a tag library and build one step by step.

The Composition of a Tag Library

There are two types of components for a tag library: the tag library descriptor file and the
tag handlers. With these a JSP is able to use tags contained in the library within its page.

The TLD File


A tag library descriptor (TLD) file is an XML document that describes the library. A TLD
contains information about the library as a whole and about each tag contained in the
library. TLDs are used by a JSP container to validate the tags.
There is typically some header information followed by elements used to define the tag
library. The elements are

<taglib> The tag library itself.


<tlibversion> The tag library's version.
<jspversion> The JSP specification version the tag library depends on.
<shortname> A simple default name with a mnemonic value. For example, <shortname>
may be used as the preferred prefix value in taglib directives and/or to create
prefixes for IDs.
<uri> A optional URI that uniquely identifies the tag library.
<info> Descriptive information about the tag library.

Then each tag contained in the library is described. There can be one or many tags per
library. There is only one TLD element required for all tags, and that is the one used to
specify a tag handler's class: <tagclass>classname</tagclass>

There are various other elements used to describe tags. Which elements a tag uses will
depend on how the tag is implemented in the handler. We'll get to that discussion in the
section below.

If a tag has attributes associated with it, then each attribute must be described within the
<tag> element. If an attribute is required by a tag, <required> is set to "true" or "yes".
To allow a runtime expression value to be used by the tag, the <rtexpvalue> is set to
"true" or "yes". For each attribute of a tag, a Bean-like getter/setter method needs to be
defined in the handler class. It's also possible to define scripting variables for use in tags.
This is accomplished using a TagExtraInfo class and will be discussed in the tag handler
section. If a TagExtraInfo is to be used, the class must be defined using the
<teiclass>classname<teiclass> within the tag definition.

A sample TLD named oreillySample.tld looks like

<?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>oreillySamples</shortname>
<info>OReilly Sample Tag library</info>
<!-A Simple tag -->
<tag>
<name>hello</name>
<tagclass>oreilly.examples.Hello </tagclass>
<!--Body content can have a value of
empty: no body
JSP: body that is evaluated by container, then possibly
processed by the tag
tagdependent: body is only processed by tag; JSP in body is not
evaluated.
-->
<bodycontent>empty</bodycontent>
<info>
This is a simple hello tag.
</info>
<!-- Optional attributes -->
<!- personalized name -->
<attribute>
<name>name</name>
<required>false</required>
<rtexpvalue>false</rtexpvalue>
</attribute>
</tag>
</taglib>

The Tag Handler


The tag is defined in a handler class. TagSupport is the base class used for simple tags.
It can be found in the javax.servlet.tagext package. What your tag is implementing
will depend on what methods could potentially be called and what needs to be
implemented. TagSupport and TagBodySupport supply default implementations of the
methods listed below.

If your Tag Handler: You need to implement the following methods:


has no attributes and no body doStartTag, doEndTag, release
has attributes doStartTag, doEndTag, set/getAttribute1...N
has a body with no interaction doStartTag, doEndTag, release
has a body with interaction doStartTag, doEndTag, release, doInitBody, doAfterBody

A more advanced feature is the use of scripting variables. Typically an attribute is passed
to the tag that contains the ID of the object to be used. The usual operation is that the tag
handler retrieves a scripting variable value object using
pageContext.getAttribute(name), performs some processing on it, and then sets the
scripting variable's value using the pageContext.setAttribute(name, object). In
addition to setting the value of the variable within the tag handler, you must define a class
derived from TagExtraInfo that provides information to the JSP container about the
nature of the variable. That class is then listed in the <teiclass> attribute of the tag.

The Java code for the tag defined in the oreillySample.tld file would look like

package oreilly.examples
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
/**
* This is a simple tag example to show how content is added to the
* output stream when a tag is encountered in a JSP page.
*/
public class Hello extends TagSupport {
private String name=null;
/**
* Getter/Setter for the attribute name as defined in the tld
file
* for this tag
*/
public void setName(String value){
name = value;
}

public String getName(){


return(name);
}
/**
* doStartTag is called by the JSP container when the tag is
encountered
*/
public int doStartTag() {
try {
JspWriter out = pageContext.getOut();
out.println("<table border="\1\">");
if (name != null)
out.println("<tr><td> Hello " + name + " </td></tr>");
else
out.println("<tr><td> Hello World </td></tr>");
} catch (Exception ex) {
throw new Error("All is not well in the world.");
}
// Must return SKIP_BODY because we are not supporting a
body for this
// tag.
return SKIP_BODY;
}
/**
* doEndTag is called by the JSP container when the tag is closed
*/
public int doEndTag(){
try {
JspWriter out = pageContext.getOut();
out.println("</table>");
} catch (Exception ex){
throw new Error("All is not well in the world.");
}
}
}

Next page: The JSP

The JSP

Once your TLD and tag handlers are created, you can begin accessing the tags in your JSP.
You declare that a JSP page will use tags defined in a tag library by including a taglib
directive in the page before any custom tag is used. The prefix attribute is a shortcut to
referencing the library throughout the page.

Sample Hello.jsp:

<%@ taglib uri="/oreillySample.tld" prefix="sample" %>


<html>
<head>
<title>Your Standard Hello World Demo</title>
</head>
<body bgcolor="#ffffff">
<hr />
<sample:hello name="Sue"/>
<hr />
</body>
</html>

The HTML source output from this JSP would look like:
<html>
<head>
<title>Your Standard Hello World Demo</title>
</head>
<body bgcolor="#ffffff">
<hr />
<table border="1">
<tr><td> Hello Sue </td></tr>
</table>
<hr />
</body>
</html>

You can see how the tag was evaluated and the contents of the tag inserted into the
output stream.

If you wanted to add functionality to our tag to make it more flexible, say to evaluate a
body a certain number of times and make the name attribute evaluated at runtime, you
can do so fairly easily with a few changes. First you would make the following changes to
the TLD file. The tag definition would look like

<tag>
<name>hello</name>
<tagclass>oreilly.examples.Hello </tagclass>
<!-- Allow for a body to be included for this tag -->
<bodycontent>JSP</bodycontent>
<info>
This is a simple hello tag.
</info>

<!-- Optional attributes -->


<!-- personalized name -->
<attribute>
<name>name</name>
<required>false</required>
<rtexpvalue>true</rtexpvalue>
</attribute>
<!-allow for the jsp coder to specify how many times to iterate
-->
<attribute>
<name>iterations</name>
<required>false</required>
<rtexpvalue>false</rtexpvalue>
</attribute>

</tag>

Then you must alter the handler class by extending TagBodySupport and implementing
the body methods if you wanted different behavior from that provided in the base class
implementation. The handler class would now look like

public class Hello extends BodyTagSupport {


private String name=null;
private int iterations=1;

/**
* Getter/Setter for the attribute name as defined in the tld
file
* for this tag
*/
public void setName(String value){
name = value;
}

public String getName(){


return(name);
}
/**
* Getter/Setter for the attribute iterations as defined in the
tld file
* for this tag
*/

public void setIterations(String value){


try {
iterations = Integer.parseInt(value);
} catch(NumberFormatException nfe) {
iterations = 1;
}
}

public String getIterations(){


return(Integer.toString(iterations));
}

public int doStartTag() throws JspTagException{


try {
JspWriter out = pageContext.getOut();
out.println("<table border=\"1\">");
if (name != null)
out.println("<tr><td> Hello " + name + " </td></tr>");
else
out.println("<tr><td> Hello World <td></tr>");
} catch (Exception ex) {
throw new JspTagException("All is not well in the world."
+ ex );
}
// Evaluate the body if there is one
return EVAL_BODY_TAG;
}

public int doEndTag()throws JspTagException {


try {
JspWriter out = pageContext.getOut();
out.println("</table>");
} catch (Exception ex){
throw new JspTagException("All is not well in the
world." + ex);
}
}

public int doAfterBody() throws JspTagException {


if (iterations-- >= 1) {
BodyContent body = getBodyContent();
try {
// Make sure we put anything in the output stream in
the
// body to the output stream of the JSP
JspWriter out = body.getEnclosingWriter();
out.println(body.getString());
body.clearBody(); // Clear for next evaluation
} catch(IOException ioe) {
throw new JspTagException("Error in Hello tag doAfterBody " +
ioe);
}
return(EVAL_BODY_TAG);
} else {
return(SKIP_BODY);
}
}

Now let's make the simple changes in the JSP file. Our sample Hello.jsp looks like

<%@ taglib uri="/oreillySample.tld" prefix="sample" %>


<%!
// allow a username to be passed in the request
String userName = request.getParameter("NAME");
%>

<html>
<head>
<title>Your Standard Hello World Demo</title>
</head>
<body bgcolor="#ffffff">
<hr />
<sample:hello name="<%= userName %>" iterations="2">
<tr><td><b>Have a nice day</b></td></tr>
</sample:hello>
<hr />
</body>
</html>

If our JSP page was called like hello.jsp?NAME=Sue our output would look like

<html>
<head>
<title>Your Standard Hello World Demo</title>
</head>
<body bgcolor="#ffffff">
<hr />
<table border="1">
<tr><td> Hello Sue </td></tr>
<tr><td><b>Have a nice day</b></td></tr>
<tr><td><b>Have a nice day</b></td></tr>
</table>
<hr />
</body>
</html>

This simple example is but a small glimpse at the power of custom tag libraries. We
examined how to create and use a simple tag library and then easily extend its
functionality. The next article will examine some of the advanced features of tags,
including defining scripting variables and cooperating tags. It will also go through working
examples of each.

Sue Spielman is an associate editor for ONJava.com, covering JSP and Servlets
technologies. She is also President and Senior Consulting Engineer for Switchback
Software LLC.
• can anyone solve my doubt
2007-11-28 09:36:45 laxmi001 [Reply | View]

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


<test:connect (i have given values for the attributes to connect to data base)/>
<test :update (here i was inserted value to update the table)/>

can i use like this i.e connect.java one class and update.java is another class if i call the
class in the jsp as enclosed above jsp will it recognise tags(ie attribute in the tld),will it
forwards the request to the update class.

When iam trying its not forwarding just it executing only connect class, and its not
forwarding to the update class.

• can anyone solve my doubt


2007-11-28 09:34:44 laxmi001 [Reply | View]

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


<test:connect (i have given values for the attributes to connect to data base)/>
<test :update (here i was inserted value to update the table)/>

can use like this ie connect one class and update is another class if i call the class in the
jsp as enclosed above will it recognise tags(ie attribute in the tld),will it forwards the
request to the update class.

• change the tld file there is a spelling mistake in tag name


2007-09-27 04:06:09 sathya_k_83 [Reply | View]

<attribute>
<name>adminPwd</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>

</attribute>

rtexprvalue is the correct spelling

• error in tld
2007-09-27 03:51:54 sathya_k_83 [Reply | View]

<attribute>
<name>adminId</name>
<required>false</required>
<rtexpvalue>false</rtexpvalue>
</attribute>

if the required and rtexpvalue are tag are inserted , the eclipse SDK is showing error

The content of element type "attribute" must match


"(name,required?,rtexprvalue?,type?,description?)".

even after inserting the above tags it is showing the error

• How to include jsp include directive in JspWriter


2007-07-17 23:31:18 Madhukar29 [Reply | View]

I have my requirement like this

buffer.append("<table width="+tableWidth+" height="+tableHeight+">"


+
"<tr>" +
"<td class="+cssTableBackGround+">" +
NBSP2+
"" +
"<img id='"+ID+"' border="+0+" src="+imageDown+"
name='toggleImage'/> (\"javascript:simpleToggle('"+ADVANCED+"',) "
+
NBSP2+
"<font class="+cssClass+"> "+
"Edit ChairPerson" +
"</td></tr></table>" +
"<div id='"+ADVANCED+"' style='background-
color:#cccccc;display:none;
overflow:hidden;height:95px;width:75%'>"+
"<%@ include file=\"advancedEpanded.jsp\" %>" +
"</div>");

JspWriter out = pc.getOut();


out.write(buffer.toString());

i need to include another jsp in the code.


is there a way to do it?
i tried with jsp include also. but i canot see the content ont the screen.

• How to include jsp include directive in JspWriter


2007-07-17 23:03:12 Madhukar29 [Reply | View]

I have my requirement like this

buffer.append("<table width="+tableWidth+" height="+tableHeight+">"


+
"<tr>" +
"<td class="+cssTableBackGround+">" +
NBSP2+
"" +
"<img id='"+ID+"' border="+0+" src="+imageDown+"
name='toggleImage'/> (\"javascript:simpleToggle('"+ADVANCED+"',) "
+
NBSP2+
"<font class="+cssClass+"> "+
"Edit ChairPerson" +
"</td></tr></table>" +
"<div id='"+ADVANCED+"' style='background-
color:#cccccc;display:none;
overflow:hidden;height:95px;width:75%'>"+
"<%@ include file=\"advancedEpanded.jsp\" %>" +
"</div>");

JspWriter out = pc.getOut();


out.write(buffer.toString());

i need to include another jsp in the code.


is there a way to do it?
i tried with jsp include also. but i canot see the content ont the screen.

• Error occured while loading the class


2006-06-18 23:50:57 Greeny [Reply | View]

org.apache.jasper.JasperException: /Hello2/Hello2.jsp(7,16) Unable to load


class hellooo
please help me to solve this

• ERROR WHILE DISPLAYING JSP


2005-09-10 10:02:58 kingviju [Reply | View]

ERROR WHILE DISPLAYING JSP :


HTTP Status 500 -

--------------------------------------------------------------------------------

type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling
this request.

exception

org.apache.jasper.JasperException: /Hello.jsp(9,4) No such tag hello in the tag library


imported with prefix sample
at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:49)
at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:383)
at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:174)
at org.apache.jasper.compiler.Parser.parseCustomTag(Parser.java:660)
at org.apache.jasper.compiler.Parser.parseElements(Parser.java:759)
at org.apache.jasper.compiler.Parser.parse(Parser.java:77)
at org.apache.jasper.compiler.ParserController.parse(ParserController.java:157)
at org.apache.jasper.compiler.ParserController.parse(ParserController.java:111)
at org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:183)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:327)

I am using Tomcat4.1. And IntelliJ IDEA.


This IDE shows that my JSP which is having following statement :
<%@ taglib uri="oreillySample" prefix="sample"%>

Cannot Resolve tag library.

CAN SOMEBODY HELP ME IDENTIFY..WHERE AM I GOING WRONG ????

Here is my source code you can refer !!!!

---- JSP
<%@ page session="false" %>
<%@ taglib uri="oreillySample" prefix="sample"%>

<html>
<head>
<title>Your Standard Hello World Demo</title>
</head>
<body bgcolor="#ffffff">
<hr />
<sample:hello name="Sue"/>
<hr />
</body>
</html>
--- TLD
<?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>oreillySample</shortname>
<info>OReilly Sample Tag library</info>

<tag>
<name>Hello</name>
<tagclass>oreilly.examples.HelloTag</tagclass>
<bodycontent>empty</bodycontent>
<attribute>
<name>name</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>

</taglib>

--- WEB.XML

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>

<display-name>
Tag Lib
</display-name>

<welcome-file-list>
<welcome-file>Hello.jsp</welcome-file>
</welcome-file-list>

<taglib>
<taglib-uri>oreillySample</taglib-uri>
<taglib-location>/WEB-INF/tlds/oreillySample.tld</taglib-location>
</taglib>

</web-app>

--- HelloTag.java

package oreilly.examples;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
/**
* This is a simple tag example to show how content is added to the
* output stream when a tag is encountered in a JSP page.
*/
public class HelloTag extends TagSupport {
private String name=null;
/**
* Getter/Setter for the attribute name as defined in the tld file
* for this tag
*/
public void setName(String value){
name = value;
}

public String getName(){


return(name);
}

/**
* doStartTag is called by the JSP container when the tag is encountered
*/
public int doStartTag() {
try {
JspWriter out = pageContext.getOut();
out.println("<table border=1>");
if (name != null)
out.println("<tr><td> HelloTag " + name + " </td></tr>");
else
out.println("<tr><td> HelloTag World </td></tr>");
} catch (Exception ex) {
throw new Error("All is not well in the world.");
}
// Must return SKIP_BODY because we are not supporting a body for this
// tag.
return SKIP_BODY;
}
/**
* doEndTag is called by the JSP container when the tag is closed
*/
public int doEndTag(){
try {
JspWriter out = pageContext.getOut();
out.println("</table>");
} catch (Exception ex){
throw new Error("All is not well in the world.");
}
return EVAL_PAGE;
}
}

The file structure is as follows :

Ch04
Hello.jsp
-> WEB-INF
web.xml
-->src\oreilly.examples.HelloTag.java
-->classes\oreilly.examples.HelloTag.class
-->tlds\oreillySample.tld

o ERROR WHILE DISPLAYING JSP


2006-11-09 21:20:32 indu_y [Reply | View]

xml parsing error in file.document root element taglib must match document type
element "null"

o ERROR WHILE DISPLAYING JSP


2005-09-10 10:07:47 kingviju [Reply | View]
I GOT THE PROBLEM RESOLVED. Simple mistake in jsp....

Error :
<sample:hello name="Sue"/>

Resolved :
<sample:Hello name="Sue"/>

Now everthing is working fine !!

• hello.jsp with iterations not working


2005-07-28 05:08:41 RachelMary [Reply | View]

hai,
i'm new to struts and was going through the examples,with iterations but
it is giving me some errors...In the example no method is written for getBodyContent();
I'm attaching the exception which came...
org.apache.jasper.JasperException: /Hello.jsp(13,2) jasper.error.bad.bodycontent.type
org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:39)
org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:409)
org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:90)
org.apache.jasper.compiler.Parser.parseBody(Parser.java:1809)
org.apache.jasper.compiler.Parser.parseOptionalBody(Parser.java:1060)
org.apache.jasper.compiler.Parser.parseCustomTag(Parser.java:1367)
org.apache.jasper.compiler.Parser.parseElements(Parser.java:1560)
org.apache.jasper.compiler.Parser.parse(Parser.java:126)
org.apache.jasper.compiler.ParserController.doParse(ParserController.java:220)
org.apache.jasper.compiler.ParserController.parse(ParserController.java:101)
org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:203)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:470)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:451)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:439)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:511)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:295)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

can any one help me in solving

RachelMary

• Error in sample code


2005-07-15 03:31:19 Amit_J [Reply | View]

Dear Sir/Madam,

I had read the article on the website about JSP Custom Tag Library. It's really very
good.
But during that I found one error in the sample code.
I request to u check and make it corrected.
The exaple is at the url.

http://www.onjava.com/pub/a/onjava/2000/12/15/jsp_custom_tags.html

The function in Hello.java


public int doAfterBody(){

}
must have to return integer but in code the return statement is missing.
Thanking you.
Amit Jadhav

• help needed to create a mail server


2005-03-01 19:54:35 prabhu_studs [Reply | View]

hi all i am amature java programmer, i am trying to create a new intranet mail server i
have to my knowledge done everything correct all modules or working properly.I am in
the event of integrating the project at this juncture in my main jsp file which has a
customtag. this customtag calls a ejb and which in returns a boolean value which
indicates the authenticity of the user.with this boolean i need to redirect the user to the
next page. i need to get the value from the customtag and need to perform the check. if
any one could help me in that regard it would be of great help to me.my mail id is
prabhu_studs@yahoo.com please feel free to contact me.

• doEndTag
2004-07-08 12:00:38 jkronz [Reply | View]

What is the int this method is supposed to return? the author never has a return
statement in his code, and therefore it never compiles..

o doEndTag
2005-06-25 17:01:32 MurderCityWeb [Reply | View]

The missing return is:

return EVAL_PAGE;

Fortunately it is documented in the javadoc for the doEndTag() method:

http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/jsp/tagext/TagSupport.
html#doEndTag()

o doEndTag
2005-04-18 05:11:28 madhukumar [Reply | View]

What is the int this method is supposed to return? the author never has a return
statement in his code, and therefore it never compiles..

• Errors in the sample code


2004-06-25 00:21:09 sjsobol [Reply | View]

Couple issues I found that caused problems for me:

Some of the comments have typos - fj_rodriguez [Reply | View]

Java-Source.Net contains a list of JSP Tag Libraries

JSP Tag Libraries


2007-03-27 01:33:42 anirtha_1980 [Reply | View]

• help trying tu run it


2003-10-29 14:56:14 anonymous2 [Reply | View]

I'm trying to run the example but I cant understant how they need be installed.

can you give the step?


what should I use to compile the TLD file
thanks

help trying tu run it


2003-10-29 14:59:34 Sue Spielman [Reply | View]

The TLD file doesn't get compiled separately. The container uses it the way it is. It
just needs to be in the WEB-INF directory.

 help trying tu run it


2004-06-25 00:24:00 sjsobol [Reply | View]

Specifically, the class file containing the tag library handler needs to go in WEB-
INF/classes. (At least, that's right for Jetty, which is what I use. Should be the
same for Tomcat.)

 help trying tu run it


2004-06-25 00:29:12 sjsobol [Reply | View]

I forgot to add this...

I use Apache to serve HTML/PHP. I am using Jetty to serve JSP files and servlets
from the same directory as the HTML and PHP files. In my case, the example
given by Sue required me to put the TLD file in the top directory of the website,
not under WEB-INF. So it depends on what your specific setup is.

 help trying to run it


2004-06-29 18:00:41 jeepzy3 [Reply | View]

I made the corrections posted by sjsobol, moved the TLD file to the top
level(was previously getting an error as well), but still can't seem to get this
to work.

I am getting error:
org.apache.jasper.JasperException: /hello.jsp(7,16) Unable to load class hello

hello.jsp
<%@ taglib uri="/oreillySample.tld" prefix="sample" %>
<html>
<head>
<title>Your Standard Hello World Demo</title>
</head>
<body bgcolor="#ffffff">
<hr />
<sample:hello name="Sue"/>
<hr />
</body>
</html>

Any ideas of what else I can check? -- thanks

• Answer to: what goes where :


2003-07-02 03:41:34 anonymous2 [Reply | View]

put the files in this order:

jsp file in any root dir of your container


tld file will always be in WEB-INF/tlds/
class file will in WEB-INF/classes/

hope this helps


Mac

• what goes where?


2003-03-02 13:03:52 ahuimanu [Reply | View]

I am working through one of James Goodwill's examples and can't, for the life of me,
figure out EXACTLY what goes where:

1) the .class file for the tag


2) the .tld file
3) the JSP

In fact, I get the following HTTP 500 error right now:

org.apache.jasper.JasperException: Unable to compile class for JSP

An error occurred at line: -1 in the jsp file: null

Generated servlet error:


[javac] Compiling 1 source file

C:\tomcat\work\Standalone\localhost\babb\welcome_jsp.java:96: cannot resolve


symbol
symbol : class HelloTag
location: class org.apache.jsp.welcome_jsp
HelloTag _jspx_th_babb_hello_0 = (HelloTag)
_jspx_tagPool_babb_hello.get(HelloTag.class);
^
C:\tomcat\work\Standalone\localhost\babb\welcome_jsp.java:96: cannot resolve
symbol
symbol : class HelloTag
location: class org.apache.jsp.welcome_jsp
HelloTag _jspx_th_babb_hello_0 = (HelloTag)
_jspx_tagPool_babb_hello.get(HelloTag.class);
^
C:\tomcat\work\Standalone\localhost\babb\welcome_jsp.java:96: cannot resolve
symbol
symbol : class HelloTag
location: class org.apache.jsp.welcome_jsp
HelloTag _jspx_th_babb_hello_0 = (HelloTag)
_jspx_tagPool_babb_hello.get(HelloTag.class);
^
3 errors

at
org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:130
)
at org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:293)
at org.apache.jasper.compiler.Compiler.generateClass(Compiler.java:340)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:352)
at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:474)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:184)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at
org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684)
at
org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:43
2)
at
org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:356)
at login.doPost(login.java:48)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.ja
va:247)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:260
)
at
org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(St
andardPipeline.java:643)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at
org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(St
andardPipeline.java:643)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2415)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
at
org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(St
andardPipeline.java:643)
at
org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:170)
at
org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(St
andardPipeline.java:641)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
at
org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(St
andardPipeline.java:641)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
at
org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(St
andardPipeline.java:643)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:432)
at
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(
Http11Protocol.java:386)
at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:534)
at
org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:530)
at java.lang.Thread.run(Thread.java:536)

Any thoughts?
J

what goes where?


2003-06-17 08:33:40 anonymous2 [Reply | View]

Hi

Did you solve your problem. Because I've the same problem error at line -1 in jsp
file: null
and I don't know how to solve it.

• corrected files (including web.xml)


2003-02-14 09:59:11 anonymous2 [Reply | View]

JSP
---

<%@ taglib uri="/WEB-INF/oreillySample.tld" prefix="sample" %>


<html>
<head>
<title>Your Standard Hello World Demo</title>
</head>
<body bgcolor="#ffffff">
<hr />
<sample:hello name="Sue"/>
<hr />
</body>
</html>

JAVA
----

package com.ml.gmi.edsi.ipro.client.action.testClasses;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
/**
* This is a simple tag example to show how content is added to the
* output stream when a tag is encountered in a JSP page.
*/
public class Hello extends TagSupport {
private String name=null;
/**
* Getter/Setter for the attribute name as defined in the tld file
* for this tag
*/
public void setName(String value){
name = value;
}

public String getName(){


return(name);
}

/**
* doStartTag is called by the JSP container when the tag is encountered
*/
public int doStartTag() {
try {
JspWriter out = pageContext.getOut();
out.println("<table border=1>");
if (name != null)
out.println("<tr><td> Hello " + name + " </td></tr>");
else
out.println("<tr><td> Hello World </td></tr>");
} catch (Exception ex) {
throw new Error("All is not well in the world.");
}
// Must return SKIP_BODY because we are not supporting a body for this
// tag.
return SKIP_BODY;
}
/**
* doEndTag is called by the JSP container when the tag is closed
*/
public int doEndTag(){
try {
JspWriter out = pageContext.getOut();
out.println("</table>");
} catch (Exception ex){
throw new Error("All is not well in the world.");
}
return EVAL_PAGE;
}
}

TLD:
---

<?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>oreillySamples</shortname>
<info>OReilly Sample Tag library</info>
<tag>
<name>hello</name>
<tagclass>com.ml.gmi.edsi.ipro.client.action.testClasses.Hello</tagclass>
<bodycontent>empty</bodycontent>
<attribute>
<name>name</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
</taglib>

WEB.XML
--------

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>

<!-- Action Servlet Configuration -->


<servlet>
<servlet-name>action</servlet-name>
<servlet-class>com.ml.gmi.edsi.ipro.client.action.IPROActionServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>

<!-- Action Servlet Mapping -->


<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

<taglib>
<taglib-uri>/WEB-INF/oreillySample.tld</taglib-uri>
<taglib-location>/WEB-INF/oreillySample.tld</taglib-location>
</taglib>

</web-app>

• Wow Wouldn't it be nice if we provided a working example


2003-02-04 09:19:20 anonymous2 [Reply | View]

This is rediculous, there are so many problems with the associated code maybe we
should consider making this example a working one.

• Missing a return value for doEndTag()


2002-01-20 05:11:34 taranjeet [Reply | View]

Missing a return integer value.

public int doEndTag()throws JspTagException {


try {
JspWriter out = pageContext.getOut();
out.println("</table>");
} catch (Exception ex){
throw new JspTagException("All is not well in the world." + ex);
}
return EVAL_BODY_TAG;
}

after that no error.


Nice Custom Tag

• Code for doEndTag() is missing a return value


2001-09-19 09:53:08 violinner [Reply | View]

Page URL:
http://www.onjava.com/pub/a/onjava/2000/12/15/jsp_custom_tags.html?page=2

Code for doEndTag() is missing a return value:

public int doEndTag()throws JspTagException {


try {
JspWriter out = pageContext.getOut();
out.println("</table>");
} catch (Exception ex){
throw new JspTagException("All is not well in the world." + ex);
}
}

• Error while compiling the jsp file


2001-08-08 21:55:58 babloosony [Reply | View]

I am getting the below error when i run the Hello.jsp:

The attribute 'name' for custom tag 'hello' on line '12' of page '/Hello.jsp' has a request
time expression as an attribute value but is not declared to accept them in its TLD.

The .tld file is same as the one given in the example.

• Typo in TLD file


2001-08-08 05:24:16 lpleva [Reply | View]

Instead of:
<rtexpvalue>true</rtexpvalue>
should be:
<rtexprvalue>true</rtexprvalue>

libor p.

• repost of typo correction


2001-05-30 15:36:16 mdwchang [Reply | View]

Looks like the form handler on this site doesn't replace html with special characters, so
let me give it another try -- in doStartTag, on the first out.println, the escape character
for the first quote (") should be put before the quote, not after the quote.

mike

• Typo in DoStartTag?
2001-05-30 15:34:14 mdwchang [Reply | View]

I believe there is a typo in the first out.println statement -- I'm not sure if this is
causing the error the previous poster spoke about.

The line should probably be:


out.println("<table border=\"1\">");
^^
/**
* doStartTag is called by the JSP container when the tag is encountered
*/
public int doStartTag() {
try {
JspWriter out = pageContext.getOut();
out.println("<table border="\1\">");
if (name != null)
out.println("<tr><td> Hello " + name + " </td></tr>");
else
out.println("<tr><td> Hello World </td></tr>");
} catch (Exception ex) {
throw new Error("All is not well in the world.");
}
// Must return SKIP_BODY because we are not supporting a body for this
// tag.
return SKIP_BODY;
}

• Error when using Custom Tags


2001-05-30 07:42:27 msprakasam [Reply | View]

hi,

I got this Error when i am using this simple Custom Tag.

javax.servlet.ServletException: Parse Error in JSP page: Error parsing TLD '/WEB-


INF/tlds/Sample.tld': The content beginning "(JRunTagLibraryInfo.java:63)

So, Pls get me back, how i can procced at msprakasam@hotmail.com

Thank U

Regards
Prakasam

• Error when using Custom Tags


2001-05-30 07:41:57 msprakasam [Reply | View]

hi,

I got this Error when i am using this simple Custom Tag.


Pls get me back, how i can procced at msprakasam@hotmail.com

Thank U

Regards
Prakasam

• Parse Error in the tag library descriptor


2001-05-29 03:39:08 pguillebaud [Reply | View]

I get the following error message in the browser when I run this:

Parse Error in the tag library descriptor: Element "web-app" does not allow "servlet"
here.
at
org.apache.jasper.compiler.JspParseEventListener.handleDirective(JspParseEventListener
.java:672)
at
org.apache.jasper.compiler.DelegatingListener.handleDirective(DelegatingListener.java:1
16)
at org.apache.jasper.compiler.Parser$Directive.accept(Parser.java:215)
at org.apache.jasper.compiler.Parser.parse(Parser.java:1073)
at org.apache.jasper.compiler.Parser.parse(Parser.java:1038)
at org.apache.jasper.compiler.Parser.parse(Parser.java:1034)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:182)
at org.apache.jasper.runtime.JspServlet.loadJSP(JspServlet.java:413)
at
org.apache.jasper.runtime.JspServlet$JspServletWrapper.loadIfNecessary(JspServlet.jav
a:149)
at org.apache.jasper.runtime.JspServlet$JspServletWrapper.service(JspServlet.java:161)
at org.apache.jasper.runtime.JspServlet.serviceJspFile(JspServlet.java:261)
at org.apache.jasper.runtime.JspServlet.service(JspServlet.java:369)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at org.apache.tomcat.core.ServletWrapper.handleRequest(ServletWrapper.java:503)
at org.apache.tomcat.core.ContextManager.service(ContextManager.java:559)
at
org.apache.tomcat.service.connector.Ajp12ConnectionHandler.processConnection(Ajp12
ConnectionHandler.java:156)
at org.apache.tomcat.service.TcpConnectionThread.run(SimpleTcpEndpoint.java:338)
at java.lang.Thread.run(Thread.java:475)

• Missing return statement in doEndTag example


2001-04-25 13:33:53 webarch [Reply | View]

In the first example, the doEndTag of the Hello class is missing the return statement. I
assume it was meant to be something like the following:

public int doEndTag(){


try {
JspWriter out = pageContext.getOut();
out.println("</table>");
} catch (Exception ex){
throw new Error("All is not well in the world.");
}
}

return EVAL_PAGE;

• Missing return statement in doEndTag example


2001-04-25 13:33:53 webarch [Reply | View]

In the first example, the doEndTag of the Hello class is missing the return statement. I
assume it was meant to be something like the following:

public int doEndTag(){


try {
JspWriter out = pageContext.getOut();
out.println("</table>");
} catch (Exception ex){
throw new Error("All is not well in the world.");
}
}

return EVAL_PAGE;

Das könnte Ihnen auch gefallen