Presentation is loading. Please wait.

Presentation is loading. Please wait.

JSP Custom Tags Keyton Weissinger Key Focus, Inc. 27 March 2001 OReilly Conference on Enterprise Java Santa Clara, CA.

Similar presentations


Presentation on theme: "JSP Custom Tags Keyton Weissinger Key Focus, Inc. 27 March 2001 OReilly Conference on Enterprise Java Santa Clara, CA."— Presentation transcript:

1 JSP Custom Tags Keyton Weissinger Key Focus, Inc. keytonw@mindspring.com 27 March 2001 OReilly Conference on Enterprise Java Santa Clara, CA

2 JSP Custom Tags2 Agenda, Part I Tags? Actions? Huh? Tag Interface Tag Attributes Tags and Scripting Variables BREAK

3 JSP Custom Tags3 Agenda, Part II Body Tags Nested Tags Iterating Tags Tags and the JSP Container Packaging and Deployment Wrap-up and Q&A

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

5 JSP Custom Tags5 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.

6 JSP Custom Tags6 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.

7 JSP Custom Tags7 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: The body contents…

8 JSP Custom Tags8 Alternate Tag Syntax If a tag does not contain any body contents, it can be used like this:

9 JSP Custom Tags9 The 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: The taglib directive also allows you to specify a prefix to use with a given tag library in its use in your JSP.

10 JSP Custom Tags10 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.

11 JSP Custom Tags11 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.

12 JSP Custom Tags12 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.

13 JSP Custom Tags13 Tag Interface All tag handler classes must implement the Tag interface.

14 JSP Custom Tags14 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() }

15 JSP Custom Tags15 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;

16 JSP Custom Tags16 Return Values int doStartTag() SKIP_BODY EVAL_BODY_INCLUDE int doEndTag() SKIP_PAGE EVAL_PAGE

17 JSP Custom Tags17 TagSupport Class Additions 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() In addition to those methods in Tag, the TagSupport class also provides the following:

18 JSP Custom Tags18 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 element for each tag in the library.

19 JSP Custom Tags19 TLD Elements The TLD has the following elements: The element contains all the other elements in the TLD.

20 JSP Custom Tags20 TLD Elements, cont. The element contains a element for each tag in the library. The possible sub-elements of are as follows:

21 JSP Custom Tags21 TLD Example <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> 1.0 1.1 logtags Log4J Wrapper Tags initLog com.oreilly.jsp.taglibs.logtags.InitLogTag Logging system initialization tag.

22 JSP Custom Tags22 Example Background Log4j is an open source project. Allows developers to fully control logging of an application. Fully runtime configurable. Gentle learning curve. See http://jakarta.apache.org/log4j/http://jakarta.apache.org/log4j/

23 JSP Custom Tags23 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.

24 JSP Custom Tags24 Example Background root appender1 category1 appender2 category2 appender3 category 3appender4

25 JSP Custom Tags25 Example Simple Tag Demo

26 JSP Custom Tags26 Tag Attributes A tag can have zero or more attributes. Attribute values provide information to the tags tag handler class at execution time.

27 JSP Custom Tags27 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.

28 JSP Custom Tags28 <log:logMessage message=test msg/> would call setMessage(String pMessage) with the String value test msg Tag Attribute Setters

29 JSP Custom Tags29 Attribute Data Types The signature of the attribute setter method in the tag handler class dictates the data type expected for that attribute.

30 JSP Custom Tags30 would call setOverride(boolean pOverride) with the boolean value true. Tag Attribute Setters

31 JSP Custom Tags31 Tag Attribute Value Conversion 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) Property TypeConversion Method

32 JSP Custom Tags32 JSP Container Call Sequence The JSP container call sequence goes as follows: 1.Instantiates tag handler. 2.Calls setup methods ( setPageContext(), etc). 3.Calls each setXxxx() method depending on each attributes presence in the tag. 4.Calls doStartTag(). 5.Calls doEndTag().

33 JSP Custom Tags33 Call Sequence Diagram <log:category priority=fatal 1-> setPriority() > 2-> doStartTag() Body contents. 3-> doEndTag()

34 JSP Custom Tags34 Runtime Attribute Values Attribute values can be the result of a runtime expression: <% Collection roomsCol = new ArrayList(); %> /> NOTE: This is how to handle other data types.

35 JSP Custom Tags35 Element Element There is an element in the TLD for each attribute for each tag: message true

36 JSP Custom Tags36 Example Background root appender1 category1 appender2 category2 appender3 category 3appender4

37 JSP Custom Tags37 Example Background A log4j categorys priority setting specifies the level required for a message to be logged for a given category: Debug Info Warn Error Fatal

38 JSP Custom Tags38 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(Heres a message.); myCat.info(Heres a message.); myCat.warn(Heres a message.); myCat.error(Heres a message.); myCat.fatal(Heres a message.);

39 JSP Custom Tags39 Example Tag Attribute Demo

40 JSP Custom Tags40 Tags and Scripting Variables Tags can introduce variables that can be used later in a JSP scriptlet or another custom tag.

41 JSP Custom Tags41 Tag-Introduced Scripting Variables This mechanism allows your tag to introduce a variable that you can use in scriptlets later in the JSP: <% myCat.debug(Hello!); %>

42 JSP Custom Tags42 Introduction of Scripting Variables To have your tag introduce a scripting variable, you must perform the following steps: 1.Somewhere in your tag handler class you must add your variable to one of the JSP scopes. 2.Create a TagExtraInfo class for your tag handler class and reference it in your TLD.

43 JSP Custom Tags43 Creating a Scripting Variable From TagSupport base class: void setId(String id) { this.id = id; } From your tags doStartTag() method: Category rootCat = Category.getRoot(); pageContext.setAttribute(id, rootCat, Page.APPLICATION_SCOPE);

44 JSP Custom Tags44 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) }; }

45 JSP Custom Tags45 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: NESTEDAT_BEGIN AT_END doStartTag() doEndTag() Variable Scope

46 JSP Custom Tags46 TLD Addition for TEI Class You must also add a element to your TLD: com.foo.CategoryTagExtraInfo

47 JSP Custom Tags47 Example Background SimpleAppenderTag CategoryTag LogMessageTag <log:category id="testCat" appender="myAppender … />

48 JSP Custom Tags48 Example Scripting Variable Demo

49 JSP Custom Tags49 BREAK 15 minutes.

50 JSP Custom Tags50 Body Tags Body Tags process their tag body contents. The body contents can contain JSP content.

51 JSP Custom Tags51 BodyTag Syntax An example call to a body tag: There was a fatal exception. Time:

52 JSP Custom Tags52 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; }

53 JSP Custom Tags53 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.

54 JSP Custom Tags54 JSP Container Call Sequence The JSP container call sequence is different for a body tag than it is for a simple tag: 1.Instantiates tag handler, calls setup functions. 2.Calls setters. 3.JSP container calls doStartTag(). 4.Calls setBodyContent(). 5.Calls doInitBody(). 6.Calls doAfterBody(). 7.JSP container calls doEndTag().

55 JSP Custom Tags55 Call Sequence Diagram <log:logMessage priority=fatal 1-> setPriority() > 2-> doStartTag() Body contents. 3->setBodyContent() 4-> doInitBody() 5-> doAfterBody() 6-> doEndTag()

56 JSP Custom Tags56 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.

57 JSP Custom Tags57 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 buffers content to the response stream after you have completed your tags processing.

58 JSP Custom Tags58 The out Variable out = JspWriter (JSP) out = BodyContent (tag1) out = BodyContent (tag2)... out = BodyContent (tag1) out = JspWriter (JSP)

59 JSP Custom Tags59 The out Variable, Part 1 1.At the beginning of a JSP, the JSP container sets the out variable to the JspWriter returned by the pageContext s getOut() method. 2.The container experiences body tag 1. a)Creation of Stack of JspWriter s. b)Place JSP out on stack. c)Reset out to BodyContent for tag1.

60 JSP Custom Tags60 The out Variable, Part 2 1.The JSP container experiences the second body tag, body tag 2, which is nested inside body tag 1. a)Place out from body tag 1 onto stack. b)Reset out to BodyContent for body tag 2. 2.The JSP container experiences the end of body tag 2. a)Reset out to body tag 1s BodyContent from stack.

61 JSP Custom Tags61 The out Variable, Part 3 1.The JSP container experiences the end of body tag 1. a)Reset out to the JSPs JspWriter object from stack.

62 JSP Custom Tags62 The out Variable out = JspWriter (JSP) out = BodyContent (tag1) out = BodyContent (tag2) out = BodyContent (tag1) out = JspWriter (JSP)

63 JSP Custom Tags63 Output of Body Content If your tags 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); }

64 JSP Custom Tags64 Return Values int doStartTag() SKIP_BODY EVAL_BODY_INCLUDE (NOT ALLOWED) EVAL_BODY_TAG int doAfterBody() EVAL_BODY_TAG SKIP_BODY int doEndTag() SKIP_PAGE EVAL_PAGE

65 JSP Custom Tags65 BodyTag TLD Features To instruct the JSP container that the current tag is a body processing tag, you must set the element: empty tagdependent JSP (default)

66 JSP Custom Tags66 Example Body Tag Demo

67 JSP Custom Tags67 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.

68 JSP Custom Tags68 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.

69 JSP Custom Tags69 Example Nested Tag Demo

70 JSP Custom Tags70 Iterating Tags Tags can iterate over their bodies repeatedly until a condition is met.

71 JSP Custom Tags71 Iterating Tags Iterating tags differ from other body tags: Iterating tags return EVAL_BODY_TAG from doAfterBody() until some condition is met.

72 JSP Custom Tags72 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.

73 JSP Custom Tags73 Example Iterating Tag Demo

74 JSP Custom Tags74 Tags and the JSP Container Discussion of the JSP implementation class created by the container for a JSP containing custom tags.

75 JSP Custom Tags75 Example JSP Implementation Class Demo

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

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

78 JSP Custom Tags78 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:

79 JSP Custom Tags79 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

80 JSP Custom Tags80 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

81 JSP Custom Tags81 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

82 JSP Custom Tags82 Option Two - Use In your JSP, set the uri attribute of the taglib directive to the location of your JAR file:

83 JSP Custom Tags83 Option Three – Symbolic Name You can also create a symbolic name in a taglib element in your web applications web.xml file: /logtags /WEB-INF/tlds/logtags.tld

84 JSP Custom Tags84 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:

85 JSP Custom Tags85 Example Deployment Demo

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

87 JSP Custom Tags87 Review, cont. 4.Create a subclass of TagExtraInfo if your tag introduces a scripting variable for use later in the JSP. 5.In the TagExtraInfo subclass, add code for each variable introduced. 6.Compile your tag. 7.Create a tag library descriptor (TLD) file. 8.In the TLD file, add a element for each tag in your library.

88 JSP Custom Tags88 Review, cont. 9.Inside each element, set the appropriate sub-elements for attributes, etc. 10.Optionally create a JAR file using your tag handler classes and your TLD file. 11.Deploy your tag library into the appropriate subfolder of your web application.

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

90 JSP Custom Tags90 Wrap-up and Q&A Questions?


Download ppt "JSP Custom Tags Keyton Weissinger Key Focus, Inc. 27 March 2001 OReilly Conference on Enterprise Java Santa Clara, CA."

Similar presentations


Ads by Google