Tài liệu XML, XSLT, Java, and JSP: A Case Study in Developing a Web Application- P8 pdf

50 517 0
Tài liệu XML, XSLT, Java, and JSP: A Case Study in Developing a Web Application- P8 pdf

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

10 1089-9 CH10 6/26/01 7:35 AM Page 332 332 Chapter 10 JSP Taglib: The bonForum Custom Tags The outputPathNames tag can be seen in use on the JSP page visitor_starts_chat_ frame.jsp, which presents the chat visitor with available chat subjects for a new chat Here is the custom tag as it appears on the JSP: One of the strengths of custom tags is their reusability It might seem strange, therefore, that the outputPathNames tag is used only in one place in bonForum, to output node paths to chat subject elements from the XML database.The project is a prototype, and so is the tag.The tag design attempts to include features that will make it useful in other situations when hierarchical information kept in XML needs to be transformed into sorted lists of node paths We will start by showing the descriptor and the code for the tag.We’ll continue with brief discussions of its attributes and methods, and finally we’ll include some notes on its design 10.4.1 The outputPathNames Descriptor The following listing shows the Tag element in the bonForum TLD that describes the outputPathNames custom action tag: outputPathNames de.tarent.forum.OutputPathNamesTag de.tarent.forum.BonForumTagExtraInfo JSP Outputs pathNames (node paths) from subTree of XML tree or forest (Note: ignores chatItem nodes in bonForumXML.) docName true pathToSubTreeRootNode true Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark 10 1089-9 CH10 6/26/01 7:35 AM Page 333 10.4 The OutputPathNamesTag Class 333 ancestorReplacer true nodeSeparator true Note that the only attribute that does anything in this book release of bonForum is docName 10.4.2 The outputPathNames Tag Handler The following listing shows the source code for the (stripped of its Javadoc comments, to save space): OutputPathNamesTag class package de.tarent.forum; import java.util.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; /** Outputs pathNames from subTree of an XML tree * or forest ( except chatItems! ) */ public class OutputPathNamesTag extends BodyTagSupport { TreeMap outputTable = null; Iterator iterator = null; private static BonForumStore bonForumStore = null; private static BonLogger logOPNT = null; private static boolean loggingInitialized = false; private static String logging = null; private private private private String String String String docName = “”; pathToSubTreeRootNode = “”; ancestorReplacer = “”; nodeSeparator = “”; private void log( String where, String what ) { if( logging != null ) { logOPNT.logWrite( System.currentTimeMillis( ), pageContext.getSession( ➥).getId( ), where, what ); } } /** locates bonForumStore in application */ Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark 10 1089-9 CH10 6/26/01 7:35 AM Page 334 334 Chapter 10 JSP Taglib: The bonForum Custom Tags private void findBonForumStore( ) { // code omitted here is in appendix, // and in Section 10.2.3, // “Finding Bean Methods from JSP Tags “ } /** Sets value of the docName attribute; * also initializes logging */ public void setDocName( String value ) { if( !loggingInitialized ) { logging = pageContext.getServletContext( ).getInitParameter( “Logging” ➥); logOPNT = new BonLogger( “OutputPathNamesTagLog.txt”, logging ); ➥loggingInitialized = true; System.err.println( “OutputPathNamesTag init logging:” + logging ); ➥} if ( value.equals( null ) ) { value = “bonForumXML”; } docName = value; } /** Sets value of the pathToSubTreeRootNode attribute */ public void setPathToSubTreeRootNode( String value ) { if( value.equals( null ) ) { value = “”; } pathToSubTreeRootNode = value; } /** Sets value of the ancestorReplacer attribute */ public void setAncestorReplacer( String value ) { if( value.equals( null ) ) { value = “”; } ancestorReplacer = value; } /** Sets value of the nodeSeparator attribute */ public void setNodeSeparator( String value ) { if( value.equals( null ) ){ value = “”; } nodeSeparator = value; } Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark 10 1089-9 CH10 6/26/01 7:35 AM Page 335 10.4 The OutputPathNamesTag Class 335 /** Makes sure the body of the tag is evaluated */ public int doStartTag( ) throws JspException { return EVAL_BODY_TAG; } /** Gets bonforumStore, * and outputTable with pathnames; * gets iterator.and outputs first pathname */ public void doInitBody( ) throws JspException, JspTagException { findBonForumStore( ); if( bonForumStore != null ) { try { outputTable = new TreeMap( bonForumStore.outputForumPathNames( ➥docName, pathToSubTreeRootNode, ancestorReplacer, nodeSeparator ) ); if ( outputTable != null ) { iterator = outputTable.keySet( ).iterator( ); if( iterator.hasNext( ) ) { pageContext.setAttribute( “output”, ( String ➥)iterator.next( ) ); } } } catch ( Exception ex ) { log( “err”, “caught Exception in OutputPathNamesTag doInitBody” ➥); throw new JspTagException( “caught Exception in OutputPathNamesTag ➥doInitBody” ); } } } /** Iterates outputTable into “output” page attribute until done */ public int doAfterBody( ) throws JspException, JspTagException { if( bonForumStore != null && outputTable != null && iterator != null ) { ➥try { if( iterator.hasNext( ) ) { pageContext.setAttribute( “output”, ( String )iterator.next( ) ➥); return EVAL_BODY_TAG; } else { bodyContent.writeOut( bodyContent.getEnclosingWriter( ) ); ➥return SKIP_BODY; } } catch ( java.io.IOException ex ) { log( “err”, “caught IOException in OutputPathNamesTag ➥doAfterBody” ); throw new JspTagException( “caught IOException in Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark 10 1089-9 CH10 6/26/01 7:35 AM Page 336 336 Chapter 10 JSP Taglib: The bonForum Custom Tags ➥OutputPathNamesTag doAfterBody” ); } } else { //log( “”, “ERROR: OutputPathNamesTag doAfterBody no store ➥table | no iterator” ); return SKIP_BODY; } } } | no Code that is common to more than one Tag Handler class was already explained For that, refer to the following sections: n n n n n Section Section Section Section Section 10.2.3, “Finding Bean Methods from JSP Tags” 10.2.4, “Using TreeMap for Sorted Output” 10.2.5, “Static Variables of Tag Handler Classes” 10.2.6, “Initializing the BonLogger Object” 10.2.7, “Using TagExtraInfo for Scripting Variables” With the help of those sections and Section 10.4.1, “The outputPathNames Descriptor,” you should be able to follow the code in this class.We will now discuss a few highlights The outputPathNames Tag Handler class implements the BodyTag interface by extending BodyTagSupport, which means that it can override the doInitBody() and doAfterBody() methods and set up a looping construct It takes advantage of that to output a list of node paths that will contain a variable number of items 10.4.3 Attribute-Setter Methods As usual, each tag attribute is represented by a private variable with a public property setter method in the tag handler bean.The first property method, setDocName(), replaces any null incoming value with a default value so that later code will not have to check for nulls.The other attribute methods involved are setPathToSubTreeRootNode(), setAncestorReplacer(), and setNodeSeparator() These set nulls to empty strings for now because they are not yet used by the bean method that will someday so For the meaning and allowable values of the tag attributes, we refer you to the references given in the first paragraph of Section 10.4, “The OutputPathNamesTag Class.” 10.4.4 The doStartTag() Method The doStartTag() method is overridden only to return EVAL_BODY_TAG; otherwise, the method returns SKIP_BODY.We want to always execute the methods that process the body content, doInitBody() and doAfterBody().This would be the place to switch off Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark 10 1089-9 CH10 6/26/01 7:35 AM Page 337 10.4 The OutputPathNamesTag Class 337 these methods, for example, depending upon some state or initialization parameters in the Web application 10.4.5 The doInitBody( ) Method The first body content-handling method starts off by making sure that the reference to the bonForumStore XML data wrapper object is valid, by calling findBonForumStore() When and if it is valid, the method invokes its outputForumPathNames method, passing the tag attributes as arguments.The bean method returns a TreeMap object filled with the items to use sequentially for each body content evaluation in the Tag Handler.The TreeMap returned is used to create a new one in the Tag Handler (That a new one is created here might be left over from attempts to use a synchronized TreeMap instance variable on the bean A reference to the local TreeMap method variable used on the bean might work now, but it needs to be tested first.) As an aside, note that the iterator here is of the keys in the TreeMap because these contain the sorted node paths to each chat subject node in the XML data.The values in the TreeMap object each contain the nodeKey.aKey for the node at the end of the path in the key Perhaps these should be included in the JSP output stream.They would be useful to locate the subject node directly, rather than using a method that takes the node path as an argument To return to the business at hand, the doInitBody() method continues by setting the first TreeMap key value in its iterator (if it is not empty) in the output page attribute, which is the scripting variable known to the JSP container at JSP translation time.We could just as easily simply output the key value as a string into the bodyContent output stream, which would make it show up on the browser page (after the bodyContent was written to the out JspWriter of the JSP and was flushed, if necessary) We discuss why that is not done in Section 10.2.7, “Using TagExtraInfo for Scripting Variables.” Because we are invoking a bean method that might throw an exception, we put all this in a try block Any exceptions caught cause an entry to the log for the Tag Handler class and result in throwing a new JspTagException, passing the buck to the surrounding JSP code, which should display the Web application JSP error page 10.4.6 The doAfterBody( ) Method As described in Section 10.1.4, “How Do JSP Custom Tags Work?”, the doAfterBody() method is invoked after the doInitBody() method whenever the Tag Handler class implements the BodyTag interface and returns EVAL_BODY_TAG from the doStartTag() method When the doAfterBody() method is invoked, the body content has already been evaluated into the output stream Let’s see what that means In the case of the Tag Handler instance being discussed here, the body content, as shown in Section 10.4, is this: Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark 10 1089-9 CH10 6/26/01 7:35 AM Page 338 338 Chapter 10 JSP Taglib: The bonForum Custom Tags Therefore, the body content evaluation in the output stream in this instance of the Tag Handler involves execution of the following statements, which appear in the translation of the JSP document into a servlet class source-code file in the Tomcat work folder: String output = null; output = (String) pageContext.findAttribute(“output”); out.write(“\r\n\t\t”); out.print( output ); out.write(“\r\n\t”); Again, these statements have already executed by the time the doAfterBody() method begins.You might well ask what happens if the iterator obtained is empty.The option tag would get a null in it if the page attribute did not exist.We take care of that in a kludgy manner by making sure that no empty TreeMap can be returned at the end of the outputForumPathNames() method in BonForumStore: if(outputTreeMap.size() outputChatMessages de.tarent.forum.OutputChatMessagesTag de.tarent.forum.BonForumTagExtraInfo Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark 10 1089-9 CH10 6/26/01 7:35 AM Page 341 10.5 The OutputChatMessagesTag Class 341 JSP Outputs chatMessages from subTree of XML tree or forest Attributes are reserved for future use selecting messages command true attr1 false attr2 false attr3 false 10.5.2 The outputChatMessages Tag Handler The following listing shows the source code, minus its javadoc comments, for the OutputChatMessagesTag class: package de.tarent.forum; import java.util.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; /** Outputs chat messages from a bonForum * XML Document or ForestHashtable */ public class OutputChatMessagesTag extends BodyTagSupport { TreeMap outputTable = null; Iterator iterator = null; private static BonForumStore bonForumStore = null; private static boolean loggingInitialized = false; private static BonLogger logOCMT = null; private static String logging = null; private String command = “”; Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark 10 1089-9 CH10 6/26/01 7:35 AM Page 367 10.6 XSLT and the TransformTag Class 367 Sheet for chatGuests”), we should design a more flexible means of indicating to the transform classes where and what those parameters are Here is the statement that makes the param1 argument available for use within the style sheet: processor.setStylesheetParam( “param1”, processor.createXString( param1 ) ); We mentioned before that the inXML and inXSL arguments could be either URI values or strings containing XML data or an XSL style sheet, respectively Notice here how these cases are differentiated by searching within the argument values for the beginning signature of an XML declaration (

Ngày đăng: 14/12/2013, 22:15

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan