Presentation is loading. Please wait.

Presentation is loading. Please wait.

JSP Custom Tags Welcome.

Similar presentations


Presentation on theme: "JSP Custom Tags Welcome."— Presentation transcript:

1 JSP Custom Tags Welcome.
My bio. Came from Microsoft technologies about a year and half ago. If you came from Microsoft technologies, and have any questions, let ‘em rip. At a couple points, there is too much info on a slide to see clearly. I’ll ask you to lok at your handouts. Also, rather than start off with a hello world tag, we’re going to discuss several of the simpler aspects of tags and then dive into a more useful example.

2 Agenda, Part I Tags? Actions? Huh? Tag Interface Tag Attributes
Tags and Scripting Variables Confusing vocabulary. Made worse by community. Tag basics – all tags must implement the Tag interface. Adding attributes. We’ll see these are simple properties of the underlying tag handler class. Tags can both introduce variables usable from within scriptlets and also from within other tags. This latter is especially powerful. JSP Custom Tags

3 Agenda, Part II Body Tags Nested Tags Iterating Tags
Tags and the JSP Container Packaging and Deployment Body tags are very useful – especially for custom processing of the body contents: XML/SQL/etc. Nested tags: cooperating. Often useful to loop over body contents until some condition is met. JAR file creation. Deployment: Where to put what and – if desired – how to create a symbolic name for taglib directive by customizing the web.xml. Questions: Remember, please ask them. JSP Custom Tags

4 A brief introduction to custom tags.
Tags? Actions? Huh? A brief introduction to custom tags. JSP Custom Tags

5 Definitions A “tag” is an XML element that can be used in a JSP to incorporate functionality without using scriptlet code. An “action” is the task performed by the tag. These are largely my own definitions. Use them at your own risk. ;-) JSP Custom Tags

6 Definitions, cont. A “tag handler” is basically a JavaBean that implements the Tag interface and has property setter methods corresponding to each tag attribute. The JSP container uses this class to process the tag. A “tag library” or “taglib” is a collection of one or more custom tags. JSP container generates code in the JSP implementation class using the class file for the tag handler. NOTE: The tag handler class is where most of the “heavy lifting” for the tag is done. JSP Custom Tags

7 Tag Syntax A custom tag consists of a start tag
with a taglib-identifying prefix (possibly containing attributes), a body (which can be empty) and an end tag: <log:logMessage categoryName="testCat" priority="fatal"> The body contents… </log:logMessage> NOTE: Prefix – identifies which tag library we are using. Attribute value in the tag must be delineated as a string using quotes in the tag. The underlying property can have a primitive (we’ll see the conversion later in an example). However, as we will see, we can set the value of these attributes using runtime expression which allows us to set property values that require other data types. Body contents: Ignored or output directly in simple tags. Processed in body tags. We’ll see these later, as well. You must close the tag. Never forget that tags are valid XML elements. JSP Custom Tags

8 Alternate Tag Syntax If a tag does not contain any body
contents, it can be used like this: <log:logMessage categoryName="testCat" priority="fatal" message="test"/> Again, remember that tags are XML elements. JSP Custom Tags

9 The <%@taglib%> Directive
Before using a tag library, you must inform the JSP container about the tag library using the directive before the first use of a tag: taglib uri="/logtags" prefix="log" %> The taglib directive also allows you to specify a prefix to use with a given tag library in its use in your JSP. URI == symbolic name. This is set up in web.xml for the web application. This could be a relative or full path from the root, as well – this other option does not require the customization of the web application web.xml. Prefix: How one set of tags are specified in a JSP page. The prefix is how the JSP container knows where to look for tag handlers code in generating the implementation class for the JSP. NOTE: The is is a JSP container directive, rather than a tag. JSP Custom Tags

10 Tag Libraries One or more tags can be packaged together as a “tag library.” A tag library is described in a tag library descriptor (.TLD) file. Tags from different libraries can be called from the same JSP, but each must be declared separately with its own directive and must be uniquely identified with its own prefix. Note it’s not an “action library.” ;-) TLD – This is an XML document containing data about the tags in your taglib. It contains information about each tag, their attributes, etc. We’ll see this in an example and will discuss this file in depth at that time. If you use more than one taglib in a page, each must have a prefix that is unique within the JSP. PAUSE!!!! REVIEW POINTS: Tags = JavaBean + Tag Interface. Use taglib directive to specify a taglib for use in your JSP. TRANSITION TO WHAT CAN TAGS DO. JSP Custom Tags

11 What Can Tags Do? A custom tag can: Know about its JSP environment.
Perform simple tasks. Perform formatting or other customization of output. Introduce variables usable from scriptlets later in the JSP. Work together either as nested pairs or separately. As we’ll see, tags have direct access to the PageContext for the JSP on which you are using a tag. Through this reference to the PageContext, the tag has access to everything the JSP has. Simple tasks. Retrieval of simple data for inclusion on the page. Formatting: SQL execution/XML rendering/Personalization/etc. We’ll see the introduction of scripting variables in an example. This mechanism allows easy initialization of a custom class through a tag without needing to code a scriptlet. This would allow insertion of some custom business logic without requiring the scriptlet code. Tags working together represent a very powerful mechanism that you can add to your JSP. For example, imagine a set of JDBC/SQL tags. One tag could initiate a connection to the database and another tag could use that tag’s connection. JSP Custom Tags

12 Why Are Tags Important? Simplification of complex tasks across multiple JSPs in a web application. Complex code hiding. Design tool incorporation. Portable to any JSP container. Incorporation of functionality into JSPs not using Java as the scripting language. In my day job’s application (we are an application service provider for hospitality) we use this for retrieval of a hotel date which is a business date based on auditing within the hotel. Scriptlet code can get hairy. Custom tags can hide it making JSP code maintenance easier. Perhaps the most powerful feature. Dreamweaver/UltraDev. Very useful for helping to get powerful tools into the hands of web page designers. Can use the tags on any JSP container that meets reqs of specification. The final point is specified in the spec. This requirement of tags is for later, when JSPs can use some other language than java. JSP Custom Tags

13 All tag handler classes must implement the Tag interface.
In specification, a handler class that implements the tag interface is what the JSP container is looking for. JSP Custom Tags

14 Tag Interface public interface Tag {
void setPageContext(PageContext pc) void setParent(Tag t) Tag getParent() int doStartTag() throws JspException int doEndTag() throws JspException void release() } PageContext gives access to all JSP scopes and several page attributes. The tag handler has access to everything in the JSP through this property value which is set by the JSP container. Parent – Useful in nested tags. This is set to NULL for tags not nested in other tags. We’ll see the doStartTag/doEndTag methods in action in a few minutes. The release() method gives you a place to clean up after yourself. JSP Custom Tags

15 Tag Interface Constants
The Tag interface also includes the following constants: public final static int SKIP_BODY = 0; public final static int EVAL_BODY_INCLUDE = 1; public final static int SKIP_PAGE = 5; public final static int EVAL_PAGE = 6; These constants are used to tell JSP container what to do with the tag’s body and/or what to do with the rest of the JSP page. JSP Custom Tags

16 Return Values int doStartTag() SKIP_BODY EVAL_BODY_INCLUDE
int doEndTag() SKIP_PAGE EVAL_PAGE The SKIP_BODY does just what you think: it instructs the JSP container to skip the body contents. The EVAL_BODY_INCLUDE is used only for non-body tags. It allows the contents (which is processed by the JSP container and cannot be processed by the tag) to be added to the response. SKIP_PAGE instructs the JSP container to skip processing of the remainder of the JSP page. EVAL_PAGE instructs the JSP container to continue processing the remainder of the JSP page. JSP Custom Tags

17 TagSupport Class Additions
In addition to those methods in Tag, the TagSupport class also provides the following: public static final Tag findAncestorWithClass(Tag from, Class klass) public void setId(String id) public String getId() public void setValue(String k, Object o) public Object getValue(String k) public void removeValue(String k) public Enumeration getValues() The findAncestorWithClass() method uses the getParent() method to find the parent tag handler class with a specific class. The set/getId methods are important in tags that introduce scripting variables. We’ll see this later. The set/getValue methods gives you a mechanism by which you can store information in a hashtable associated with your tag handler class. You can use this mechanism instead of instance variables. The getValues method allows you to retrieve an enumeration of keys on the above hashtable. NOTE: This hashtable implementation simply provides another way of storing a dictionary-like set of tag variables. You would still have to create setters for each of your attributes, but you could implement it internally using this hashtable provided in the TagSupport base class. JSP Custom Tags

18 Tag Library Descriptor Files
The JSP container generates code in the JSP implementation class for a tag according to information you set in the TLD. The TLD is an XML document. It contains a single <tag/> element for each tag in the library. In interpreting the tags in your JSP, the container will look at the TLD that it has cached when it first interpreted the taglib directive for the page. We’ll see a reference to its DTD in just a moment when we look at a complete TLD. JSP Custom Tags

19 TLD Elements The TLD has the following elements:
The <taglib/> element contains all the other elements in the TLD. <tlibversion/> <uri/> <jspversion/> <shortname/> The taglib versioning information is not yet needed by the JSP container, but may be useful when taglibs are incorporated into development tools. The symbolic name with which you will instruct the JSP container where to find the TLD for the tags in your JSP. The JSP version for which this taglib version was written. The short name of the tag library. A string. NOTE: JSP 1.2 extends this to allow for more detail. Let’s look at the individual tag elements themselves… JSP Custom Tags

20 TLD Elements, cont. The <taglib/> element contains a <tag/> element for each tag in the library. The possible sub-elements of <tag/> are as follows: <name/> <tagclass/> <teiclass/> <bodycontent/> <info/> <attribute/> Name – A string containing the name of the tag. This is a required element. Tagclass – Fully qualified class name, I.e. com.oreilly.jsp.taglibs.logtag.InitLog. Also required. Teiclass – The fully qualified class name of the TagExtraInfo class for this tag. The container uses this class to store information about any introduced scripting variables. This is only required for those tags that introduce scripting variables. Bodycontent – Can be JSP (default), empty, or TagDependent (like SQL, for example). If not present, JSP is assumed by the JSP container. Info – Descriptive text. Attribute – Information about each specific attribute. We’ll look at this one in detail in a few minutes when we look at adding attributes. For now, let’s look at an actual TLD example. Please see Slide #21 in your handout as this next slide will be hard to read. JSP Custom Tags

21 TLD Example <?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" " <taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <shortname>logtags</shortname> <uri></uri> <info>Log4J Wrapper Tags</info> <tag> <name>initLog</name> <tagclass> com.oreilly.jsp.taglibs.logtags.InitLogTag </tagclass> <info>Logging system initialization tag.</info> </tag> </taglib> XML version. Standard stuff. Taglib DTD from sun. For more details, see the spec. Lots of details there. Taglib version. JSP version. Shortname. Tag element – Note this taglib currently has only a single tag in it: the initLog tag. Name is case-sensitive. Must appear as initLog in a tag, or JSP container will not recognize the tag as being this one. Tagclass – JSP container will instantiate an instance of this class to handle each instance of the initLog tag. No Teiclass. Not needed. The initLog tag does not process its body and does not control validation. We’ll learn more about validation when we discuss tags that introduce scripting variables. Bodycontent element – Not required. JSP container assumes JSP. Info element. Note that there are no attributes allowed for this version of the initLog tag. It’s time to begin looking at our first example demo. But before we do, some background is in order… JSP Custom Tags

22 Example Background Log4j is an open source project.
Allows developers to fully control logging of an application. Fully runtime configurable. Gentle learning curve. See Very useful. Very light weight. Simple to use. Good open source support. Active mailing list. Good, responsive maintainer. JSP Custom Tags

23 Example Background A category is a named entity that categorizes a part of the logging space. An appender is a logging output destination. A layout is a formatter for output to an appender. Priority is the minimum level of messages to be logged for a category. Log4J allows some very powerful, very flexible formatting and configuration. We will only be using the very simplest in this example. Please note, that upon the conclusion of this conference and after a bit of polishing, I will be submitting an expanded version of the examples in this tutorial into the Jakarta taglib project for consideration. Until then it will be available from the O’Reilly site. JSP Custom Tags

24 Example Background root appender1 category1 appender2
NOTE: Categories in Log4J are set up in a parent-child relationship with logging being optionally additive (logging messages to a child could trigger a logging message being automatically sent to it’s parent’s logging targets, for example. At the “base” of this parent-child hierarchy JSP Custom Tags

25 Tag Attributes A tag can have zero or more attributes. Attribute values provide information to the tag’s tag handler class at execution time. Custom tags can have attributes of any data type, including object, though the mechanism is not as straightforward for setting attributes whose data types are not primitives or the primitive’s class type. As we’ll see, custom tag attributes are nothing more than java bean properties. JSP Custom Tags

26 Tag Attributes Each attribute has a corresponding setXxxx() method.
Each attribute value included in the tag triggers a call to its corresponding setter. No particular order. The setter called can be determined by capitalizing the first letter of the attribute name and adding the word “set” as a prefix. Same mechanism as that used by the JSP container when constructing method calls in the JSP implementation class for a JSP that uses a Javabean whose properties you are attempting to set. Note that the specification does NOT specify the order in which the setters are called. Tomcat for example calls these in alphabetical order. But other implementations may not. Do not assume any order in which the JSP container will call your setters. JSP Custom Tags

27 Tag Attribute Setters <log:logMessage message=“test msg”/>
would call setMessage(String pMessage) with the String value “test msg” To review, the prefix is specified in the taglib directive, the message results in a call in the implementation class to setMessage with the string “test msg.” Same for the override attribute. Note, that if there is no setter present in the tag handler class for an attribute you attempt to enter into a tag, the JSP container will throw an exception upon attempting to compile the JSP. JSP Custom Tags

28 Attribute Data Types The signature of the attribute setter method in the tag handler class dictates the data type expected for that attribute. Same mechanism as that used by the JSP container when constructing method calls in the JSP implementation class for a JSP that uses a Javabean whose properties you are attempting to set. Note that the specification does NOT specify the order in which the setters are called. Tomcat for example calls these in alphabetical order. But other implementations may not. Do not assume any order in which the JSP container will call your setters. JSP Custom Tags

29 Tag Attribute Setters <log:initLog override=“true”/> would call
setOverride(boolean pOverride) with the boolean value true. To review, the prefix is specified in the taglib directive, the message results in a call in the implementation class to setMessage with the string “test msg.” Same for the override attribute. Note, that if there is no setter present in the tag handler class for an attribute you attempt to enter into a tag, the JSP container will throw an exception upon attempting to compile the JSP. JSP Custom Tags

30 Tag Attribute Value Conversion
Property Type Conversion Method boolean or Boolean byte or Byte char or Character double or Double int or Integer float or Float long or Long Boolean.valueOf(String) Byte.valueOf(String) String.charAt(int) Double.valueOf(String) Integer.valueOf(String) Float.valueOf(String) Long.valueOf(String) Note this is only for non-runtime attribute values. JSP Custom Tags

31 JSP Container Call Sequence
The JSP container call sequence goes as follows: Instantiates tag handler. Calls setup methods (setPageContext(), etc). Calls each setXxxx() method depending on each attribute’s presence in the tag. Calls doStartTag(). Calls doEndTag(). Again, the order of the setters is not specified. We’ll see these steps in actions when we look at the interaction between the JSP container and the custom tags. Let’s look at this call sequence in terms of an actual tag… JSP Custom Tags

32 Call Sequence Diagram <%@ taglib …%> <log:category
priority=“fatal” > setPriority() > > doStartTag() Body contents. </log:category> > doEndTag() Before anything else, the JSP container caches information from the TLD upon processing the taglib directive. Upon interpretation of the tag, the container will create an instance of the tag handler, call its setPageContext and setParent methods (though not necessarily in that order) and then call the setPriority method. Then – and only then – would it call the doStartTag, followed by the doEndTag methods. JSP Custom Tags

33 Runtime Attribute Values
Attribute values can be the result of a runtime expression: <% Collection roomsCol = new ArrayList(); %> <log:logCollection collection="<%=roomsCol%>“/> NOTE: This is how to handle other data types. Note that if you use a variable in your runtime expression value for your attribute, the variable must be declared and initialized before it is used. The process is exactly the same in that only after the setPageContext and setParent methods are called are the setXXXXX methods called, and then the doStartTag and doEndTag methods are called. Again, this is how we will initialize those attributes whose values are not covered by the primitives and their class representations. Now, let’s see how we “tell” the JSP container about our attributes. JSP Custom Tags

34 <attribute/> Element
There is an <attribute/> element in the TLD for each attribute for each tag: <attribute> <name>message</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> For all attributes, the only required element is the name. Required – default is FALSE. Not required. Rtexprvalue – default is FALSE. Not required. JSP Custom Tags

35 Example Background root appender1 category1 appender2
Log4J allows some very powerful, very flexible formatting and configuration. We will only be using the very simplest in this example. Please note, that upon the conclusion of this conference and after a bit of polishing, I will be submitting an expanded version of the examples in this tutorial into the Jakarta taglib project for consideration. Until then it will be available from the O’Reilly site. NOTE: Categories in Log4J are set up in a parent-child relationship with logging being optionally additive (logging messages to a child could trigger a logging message being automatically sent to it’s parent’s logging targets, for example. At the “base” of this parent-child hierarchy JSP Custom Tags

36 Example Background A log4j category’s “priority” setting
specifies the “level” required for a message to be logged for a given category: Debug Info Warn Error Fatal Same mechanism as that used by the JSP container when constructing method calls in the JSP implementation class for a JSP that uses a Javabean whose properties you are attempting to set. Note that the specification does NOT specify the order in which the setters are called. Tomcat for example calls these in alphabetical order. But other implementations may not. Do not assume any order in which the JSP container will call your setters. JSP Custom Tags

37 Example Background Each category has methods corresponding to the various priorities. You use the appropriate method to log a message of a given priority for the category of interest: myCat.debug(“Here’s a message.”); myCat.info(“Here’s a message.”); myCat.warn(“Here’s a message.”); myCat.error(“Here’s a message.”); myCat.fatal(“Here’s a message.”); Same mechanism as that used by the JSP container when constructing method calls in the JSP implementation class for a JSP that uses a Javabean whose properties you are attempting to set. Note that the specification does NOT specify the order in which the setters are called. Tomcat for example calls these in alphabetical order. But other implementations may not. Do not assume any order in which the JSP container will call your setters. JSP Custom Tags

38 Tags and Scripting Variables
Tags can introduce variables that can be used later in a JSP scriptlet or another custom tag. Why would you want to do this? One very useful reason is the simple initialization of a class that tags allow. In a single tag, you can call all your property setters and fully initialize the class which processes its values based on business logic and then allows you to use that variable later in the page. Also this allows you to use a bean-like interface (with simple incorporation into JSP of property values) that could include more robust processing power. JSP Custom Tags

39 Tag-Introduced Scripting Variables
This mechanism allows your tag to introduce a variable that you can use in scriptlets later in the JSP: <log:category id=“myCat”/> <% myCat.debug(“Hello!”); %> The JSP scopes allowed: request, session, application or page. We’ll look at the TagExtraInfo class in just a moment. For now, recognize only that the JSP container uses this class to hold information about any scripting variables introduced in the tag. This information is used in the construction of implementation class code dealing with the scripting variable. From it, it knows the class of the variable which allows the container to properly cast the Object retrieved from the JSP scope in which the variable is found. This is a common mistake. Your scripting variable will not be recognized without this. If you attempt to use your introduced scripting variable without this addition to the TLD, your JSP compilation will result in an exception being thrown. NOTE: Besides their use in introducing scripting variables, the TagExtraInfo class is useful in doing translation time validation of tag attributes. We will not be covering this topic in this tutorial. JSP Custom Tags

40 Introduction of Scripting Variables
To have your tag introduce a scripting variable, you must perform the following steps: Somewhere in your tag handler class you must add your variable to one of the JSP scopes. Create a TagExtraInfo class for your tag handler class and reference it in your TLD. The JSP scopes allowed: request, session, application or page. We’ll look at the TagExtraInfo class in just a moment. For now, recognize only that the JSP container uses this class to hold information about any scripting variables introduced in the tag. This information is used in the construction of implementation class code dealing with the scripting variable. From it, it knows the class of the variable which allows the container to properly cast the Object retrieved from the JSP scope in which the variable is found. This is a common mistake. Your scripting variable will not be recognized without this. If you attempt to use your introduced scripting variable without this addition to the TLD, your JSP compilation will result in an exception being thrown. NOTE: Besides their use in introducing scripting variables, the TagExtraInfo class is useful in doing translation time validation of tag attributes. We will not be covering this topic in this tutorial. JSP Custom Tags

41 Creating a Scripting Variable
<log:category id=“myCat”/> From TagSupport base class: void setId(String id) { this.id = id; } From your tag’s doStartTag() method: Category rootCat = Category.getRoot(); pageContext.setAttribute(id, rootCat, Page.APPLICATION_SCOPE); The JSP container calls the category tag handler’s setId() method (from the TagSupport base class). The setId() method sets the instance variable, id. Using this instance variable, use the setAttribute() method of the PageContext object to create a variable using the id set above. In this next slide, we will be looking at the TagExtraInfo class. There’s a bit more information than is readable on the slide. Please look at your packet on slide #36. JSP Custom Tags

42 TagExtraInfo Class public class CategoryTagExtraInfo extends TagExtraInfo { public VariableInfo[] getVariableInfo(TagData data) { return new VariableInfo[] { new VariableInfo( data.getAttributeString("id"), "org.apache.log4j.Category", true, VariableInfo.AT_END) }; } To create the code in the implementation class that will instantiate your scripting variable, you must provide the JSP container information about that variable or variables introduced by your tag. The TEIClass provides this information using a single method called getVariableInfo(). The JSP container itself instantiates your TEI class and calls this method. The method returns an array of VariableInfo objects. There is a single VariableInfo object in the array for each scripting variable your tag handler introduces. All you need to know is what all is required for the VariableInfo class constructor: Variable name. Variable class. Whether it is a new variable and thus must be declared. Scope of the variable in the context of the variable-introducing tag. JSP Custom Tags

43 Variable Scope Tags can introduce scripting variables with one of three scopes represented by the three VariableInfo constants, NESTED, AT_BEGIN, and AT_END. The following diagram explains these three scopes: NESTED AT_BEGIN AT_END doStartTag() doEndTag() NESTED – The scripting variable will only be available in interpreting JSP content in the tag body. AT_BEGIN – The scripting variable will be available from the beginning of the tag onward through the end of the JSP. AT_END – The scripting variable will be available from the close tag onward through the end of the JSP. JSP Custom Tags

44 TLD Addition for TEI Class
You must also add a <teiclass/> element to your TLD: <teiclass> com.foo.CategoryTagExtraInfo </teiclass> This is a fully qualified class name. Not adding a TEICLASS element to your TLD is a very common mistake that will result in a variable not found exception being thrown by the container if you attempt to use a variable in a scriptlet for whom there is no TEICLASS element in the TLD. NOTE: Besides their use in introducing scripting variables, the TagExtraInfo class is useful in doing translation time validation of tag attributes. We will not be covering this topic in this tutorial. JSP Custom Tags

45 Example Background SimpleAppenderTag CategoryTag LogMessageTag
<log:simpleAppender id="myAppender" … /> <log:category id="testCat" appender="myAppender“ … /> <log:logMessage categoryName="testCat" … /> In our example program we are about to discuss and demonstrate the introduction of a scripting variable. Rather than introducing a single variable, we will be introducing two: The simpleAppender tag will introduce a file appender that you can use for the category to be instantiated later in the JSP. The Category tag will introduce a logging category that we will be able to use later in the script in a logMessage tag to instruct the message tag to which category we want to log a message. Before demonstrating the logMessage tag and logging a message, we will demonstrate the use of the Category tag in a scriptlet. Let’s dive in… JSP Custom Tags

46 Body Tags Body Tags process their tag body contents. The body contents can contain JSP content. Body tags are very useful. They allow you to perform formatting of content. Body tags are required if you have an attribute that spans multiple lines as this is a limitation of tag attributes. JSP Custom Tags

47 BodyTag Syntax An example call to a body tag:
<log:logMessage priority=“fatal”> There was a fatal exception. Time: <%=Calendar.getInstance().getTime()%> </log:logMessage> Same as before: Prefix. Start tag. Priority attribute. Multi-line body content. Close tag. JSP Custom Tags

48 BodyTag Interface public interface BodyTag extends Tag {
public final static int EVAL_BODY_TAG = 2; void setBodyContent( BodyContent b); void doInitBody() throws JspException; int doAfterBody() throws JspException; } EVAL_BODY_TAG – The return type from the doStartTag method, for body tags. We’ll discuss these in a moment. The setBodyCOntent() is what separates a true body tag from a Tag that returns EVAL_BODY_INCLUDE. The setBodyContent creates a BodyContent object and passes this into the tag handler class for use in the processing of the body. The doInitBody allows you to initialize variables for use in the processing of the body content ONLY. The doAfterBody is where the actual processing work for the body occurs. In it you will write code to interact with the BodyContent object sent in with the setBodyContent method. JSP Custom Tags

49 BodyContent Class The tag accesses its body contents through a BodyContent object which is set by the JSP container. BodyContent is a subclass of JspWriter which is used to write content to the response body. BodyContent also has several methods to manipulate (flush, clear, return as a string) the contents of the body. Note that although the flush method is implemented, you cannot flush from within a tag – doing so results in the throwing of an exception. Note that the BodyContent object contains the RESULTS of processing the body if the body contains JSP or other tags. The BodyContent object allows you to create contents to be output in the response without actually using the JspWriter assigned to “out” in the JSP. This allows you to build the response and then decide what to do with it. JSP Custom Tags

50 JSP Container Call Sequence
The JSP container call sequence is different for a body tag than it is for a simple tag: Instantiates tag handler, calls setup functions. Calls setters. JSP container calls doStartTag(). Calls setBodyContent(). Calls doInitBody(). Calls doAfterBody(). JSP container calls doEndTag(). As we stated earlier, the order of the call setters is not specified in the specification. You won’t likely use the doInitBody, but it is a useful place to do initialization required before you process the body contents. JSP Custom Tags

51 Call Sequence Diagram <%@ taglib …%> <log:logMessage
priority=“fatal” > setPriority() > > doStartTag() Body contents >setBodyContent() 4-> doInitBody() 5-> doAfterBody() </log:logMessage> 6-> doEndTag() Before anything else, the JSP container caches information from the TLD upon processing the taglib directive. Upon interpretation of the tag, the container will create an instance of the tag handler, call its setPageContext and setParent methods (though not necessarily in that order) and then call the setPriority method. Then – and only then – would it call the doStartTag. Then the setBodyContent (assuming the return of doStartTag is EVAL_BODY_TAG). Then doInitBody. Then doAfterBody Then do followed by the doEndTag methods. JSP Custom Tags

52 BodyTag Methods In most cases, it is not necessary to override the setBodyContent() method already provided in the BodyTagSupport base class. Use the doInitBody() method to initialize any variables you need for the doAfterBody(). Again this is rarely needed. The doAfterBody() is where you will do the real work of your body tag. The next slide is another that’s a bit hard to read, see in your packet for slide 49… JSP Custom Tags

53 BodyContent and out BodyContent allows you to write to a JspWriter without interfering with the JspWriter affiliated with the JSP itself. This allows you to write to an output buffer and decide whether or not to write the buffer’s content to the response stream after you have completed your tag’s processing. The next slide is another that’s a bit hard to read, see in your packet for slide 49… JSP Custom Tags

54 The out Variable <%@taglib%> out = JspWriter (JSP)
<tag1> out = BodyContent (tag1) <tag2> out = BodyContent (tag2) ... </tag2> </tag1> out = BodyContent (tag1) Before anything else, the JSP container caches information from the TLD upon processing the taglib directive. Upon interpretation of the tag, the container will create an instance of the tag handler, call its setPageContext and setParent methods (though not necessarily in that order) and then call the setPriority method. Then – and only then – would it call the doStartTag. Then the setBodyContent (assuming the return of doStartTag is EVAL_BODY_TAG). Then doInitBody. Then doAfterBody Then do followed by the doEndTag methods. JSP Custom Tags

55 The out Variable, Part 1 At the beginning of a JSP, the JSP container sets the out variable to the JspWriter returned by the pageContext’s getOut() method. The container experiences body tag 1. Creation of Stack of JspWriters. Place JSP out on stack. Reset out to BodyContent for tag1. The next slide is another that’s a bit hard to read, see in your packet for slide 49… JSP Custom Tags

56 The out Variable, Part 2 The JSP container experiences the second body tag, body tag 2, which is nested inside body tag 1. Place out from body tag 1 onto stack. Reset out to BodyContent for body tag 2. The JSP container experiences the end of body tag 2. Reset out to body tag 1’s BodyContent from stack. The next slide is another that’s a bit hard to read, see in your packet for slide 49… JSP Custom Tags

57 The out Variable, Part 3 The JSP container experiences the end of body tag 1. Reset out to the JSP’s JspWriter object from stack. The next slide is another that’s a bit hard to read, see in your packet for slide 49… JSP Custom Tags

58 The out Variable <%@taglib%>
out = JspWriter (JSP) <tag1> out = BodyContent (tag1) <tag2> out = BodyContent (tag2) </tag2> </tag1> out = BodyContent (tag1) out = JspWriter (JSP) Before anything else, the JSP container caches information from the TLD upon processing the taglib directive. Upon interpretation of the tag, the container will create an instance of the tag handler, call its setPageContext and setParent methods (though not necessarily in that order) and then call the setPriority method. Then – and only then – would it call the doStartTag. Then the setBodyContent (assuming the return of doStartTag is EVAL_BODY_TAG). Then doInitBody. Then doAfterBody Then do followed by the doEndTag methods. JSP Custom Tags

59 Output of Body Content if (null != bodyContent) { JspWriter lastOut =
If your tag’s body content should be output into the response body, you must use the writeOut() method of the BodyContent Object (from doEndTag()): if (null != bodyContent) { JspWriter lastOut = bodyContent.getEnclosingWriter(); bodyContent.writeOut(lastOut); } The JSP container starts within the current tag body’s BodyContent object, and calls its writeOut() method. It sends into this writeOut method a JspWriter that it retrieves from the BodyContent method getEnclosingWriter which returns a JspWriter which is the last JspWriter before the JspWriter reference was temporarily set to the current BodyContent. This is the “out” variable if the tag is not inside another tag. JSP Custom Tags

60 Return Values int doStartTag() SKIP_BODY
EVAL_BODY_INCLUDE (NOT ALLOWED) EVAL_BODY_TAG int doAfterBody() int doEndTag() SKIP_PAGE EVAL_PAGE Note that the EVAL_BODY_INCLUDE is not allowed in a body tag. The EVAL_BODY_TAG being returned from the doAfterBody is how you set up iteration over the body contents in the body tag. SKIP_PAGE and EVAL_PAGE work exactly as they do in Tags. JSP Custom Tags

61 BodyTag TLD Features To instruct the JSP container that the current
tag is a body processing tag, you must set the <bodycontent/> element: empty tagdependent JSP (default) If you mark it as empty, then the body should be empty. Note if your body contains anything and you set bodycontent to EMPTY, then the JSP container will throw an exception during translation phase and your JSP implementation class will not be written. Only use tagdependent only when you will be processing the body specially yourself. Note if you have it set to JSP (the default) then what you get in the BodyContent is the RESULTS of the processing of the JSP contents in the body. JSP Custom Tags

62 Nested Tags Nested actions are tags that are processed as part of the tag body content. Typically these tags rely on certain properties of the surrounding tag. Again, the example we discussed earlier of the surrounding tag being responsible for creating a JDBC connection to a database and the internal tag which executes a query will use the connection created by that surrounding tag. JSP Custom Tags

63 Nested Tags Nested tags can take two forms:
Nested tags may or may not use a variable introduced by the surrounding tag. Some nested tags rely on their surrounding tags for some information without which it will not function. JSP Custom Tags

64 Iterating Tags Tags can iterate over their bodies repeatedly until a condition is met. Iteration tags JSP Custom Tags

65 Iterating Tags Iterating tags differ from other body tags:
Iterating tags return EVAL_BODY_TAG from doAfterBody() until some condition is met. This is very straightforward. Note this will be changing somewhat in JSP 1.2. JSP Custom Tags

66 Example Background LogCollectionTag:
Takes a collection and the name of a message variable. Iterates through the collection and creates a logging message for each object. Creates a scripting variable to be used by a nested LogMessageTag. Repeats until the end of the collection. The LogCollectionTag as its name implies allows you to iterate over a collection and log a message for each object using a nested logMessage tag in the body. Rather than force the user to know what variable is introduced by the logCollection tag (this variable will contain the message), we will allow this to be set as a property. The message for each object in the collection is simple and uses only the toString() method of the object rather than attempting anything that would require more business logic. JSP Custom Tags

67 Packaging and Deployment
Tag libraries are typically packaged together into a JAR file and deployed to a JSP container. JSP Custom Tags

68 Deployment: Three Options
To deploy and use your tag library, you have three options: Set the uri attribute of the taglib directive to the location of the TLD file. Set the uri attribute of the taglib directive to the location of the JAR file. Set the uri attribute of the taglib directive to a symbolic name set in the web.xml file. JSP Custom Tags

69 Option One 1. Deploy your files:
WEB-INF/ /classes *.class /tlds logtags.tld 2. In your JSP, set the uri attribute of the taglib directive to the location of the TLD file: taglib uri=“/WEB-INF/tlds/logtags.tld” prefix=“log” %> JSP Custom Tags

70 Option Two – File Setup To create a JAR file, first arrange the files in the following folder organization: META-INF/ taglib.tld com/ oreilly/ jsp/ taglibs/ logtags/ *.class JSP Custom Tags

71 Option Two – JAR Creation
Change to the previously created folder (containing the META-INF and com folders) and execute the following: jar cvf logtags.jar META-INF com JSP Custom Tags

72 Option Two - Deployment
Copy the JAR file to the lib sub-directory of WEB_INF folder for your JSP container: WEB-INF/ lib/ logtags.jar JSP Custom Tags

73 Option Two - Use In your JSP, set the uri attribute of the taglib directive to the location of your JAR file: taglib uri=“/WEB-INF/lib/logtags.jar” prefix=“log” %> JSP Custom Tags

74 Option Three – Symbolic Name
You can also create a symbolic name in a taglib element in your web application’s web.xml file: <web-app> <taglib> <taglib-uri> /logtags </taglib-uri> <taglib-location> /WEB-INF/tlds/logtags.tld </taglib-location> </taglib> </web-app> Setting up a symbolic link is not necessary and can be more work than it’s worth. If you do not set up a symbolic link then your web application and your taglib/JSPs can live together without any knowledge of the other. JSP Custom Tags

75 Option Three – Symbolic Name Use
To use a symbolic name in your JSP, just set the uri attribute of the taglib directive to the symbolic name: taglib uri=“/logtags” prefix=“log” %> JSP Custom Tags

76 Review To create a tag library:
Create a tag handler class that implements Tag or BodyTag. In the tag handler class create setters for each attribute your tag will use. In the tag handler class place processing in the doStartTag, doEndTag, doInitBody and doAfterBody methods as needed. JSP Custom Tags

77 Review, cont. Create a subclass of TagExtraInfo if your tag introduces a scripting variable for use later in the JSP. In the TagExtraInfo subclass, add code for each variable introduced. Compile your tag. Create a tag library descriptor (TLD) file. In the TLD file, add a <tag/> element for each tag in your library. JSP Custom Tags

78 Review, cont. Inside each <tag/> element, set the appropriate sub-elements for attributes, etc. Optionally create a JAR file using your tag handler classes and your TLD file. Deploy your tag library into the appropriate subfolder of your web application. JSP Custom Tags

79 Review, cont. For each tag library you wish to use in your JSP, use the directive to instruct the JSP container how to process your tags. Use your tags in the JSP, being careful to include required attributes, etc. Enjoy the accolades of those around you for being so smart as to use tag libraries! JSP Custom Tags

80 That’s all there is! Questions? JSP Custom Tags


Download ppt "JSP Custom Tags Welcome."

Similar presentations


Ads by Google