2. Using the Tutorial Examples 3. Getting Started with Web Applications 5. JavaServer Pages Technology 7. JavaServer Pages Standard Tag Library Dynamic Attribute or Deferred Expression Encapsulating Reusable Content Using Tag Files Declaring Tag Attributes in Tag Files Declaring Tag Variables in Tag Files Evaluating Fragments Passed to Tag Files Simple and Fragment Attribute and Variable Example Top-Level Tag Library Descriptor Elements Declaring Tag Attributes for Tag Handlers Declaring Tag Variables for Tag Handlers Programming Simple Tag Handlers Including Tag Handlers in Web Applications How Is a Simple Tag Handler Invoked? Tag Handlers for Tags with Attributes Defining Attributes in a Tag Handler Setting Deferred Value Attributes and Deferred Method Attributes Tag Handlers for Tags with Bodies Tag Handler Does Not Manipulate the Body 10. JavaServer Faces Technology 11. Using JavaServer Faces Technology in JSP Pages 12. Developing with JavaServer Faces Technology 13. Creating Custom UI Components 14. Configuring JavaServer Faces Applications 15. Internationalizing and Localizing Web Applications 16. Building Web Services with JAX-WS 17. Binding between XML Schema and Java Classes 19. SOAP with Attachments API for Java 21. Getting Started with Enterprise Beans 23. A Message-Driven Bean Example 24. Introduction to the Java Persistence API 25. Persistence in the Web Tier 26. Persistence in the EJB Tier 27. The Java Persistence Query Language 28. Introduction to Security in the Java EE Platform 29. Securing Java EE Applications 31. The Java Message Service API 32. Java EE Examples Using the JMS API 36. The Coffee Break Application | Programming Simple Tag HandlersThe classes and interfaces used to implement simple tag handlers are contained inthejavax.servlet.jsp.tagext package. Simple tag handlers implement theSimpleTag interface. Interfaces can be used totake an existing Java object and make it a tag handler. For mostnewly created handlers, you would use theSimpleTagSupport classes as a base class. The heart of a simple tag handler is a single method,doTag, whichis invoked when the end element of the tag is encountered. Notethat the default implementation of thedoTag method ofSimpleTagSupport does nothing. A tag handler has access to an API that allows it tocommunicate with the JSP page. The entry point to the API is theJSP context object (javax.servlet.jsp.JspContext). TheJspContext object provides access to implicit objects.PageContextextendsJspContext with servlet-specific behavior. Through these objects, a tag handler can retrieveall the other implicit objects (request, session, and application) that are accessible froma JSP page. If the tag is nested, a tag handler also hasaccess to the handler (called theparent) that is associated with the enclosingtag. Including Tag Handlers in Web ApplicationsTag handlers can be made available to a web application in two basicways. The classes implementing the tag handlers can be stored in an unpackedform in the/WEB-INF/classes/ subdirectory of the web application. Alternatively, if the libraryis distributed as a JAR, it is stored in the/WEB-INF/lib/ directoryof the web application. How Is a Simple Tag Handler Invoked?TheSimpleTag interface defines the basic protocol between a simple tag handler anda JSP page’s servlet. The JSP page’s servlet invokes thesetJspContext,setParent, andattribute setting methods before callingdoStartTag. ATag t = new ATag();t.setJSPContext(...);t.setParent(...);t.setAttribute1(value1);t.setAttribute2(value2);...t.setJspBody(new JspFragment(...))t.doTag(); The following sections describe the methods that you need to develop for eachtype of tag introduced inTypes of Tags. Tag Handlers for Basic TagsThe handler for a basic tag without a body must implement thedoTagmethod of theSimpleTag interface. ThedoTag method is invoked when the end elementof the tag is encountered. The basic tag discussed in the first section,<tt:basic />, would be implementedby the following tag handler: public HelloWorldSimpleTag extends SimpleTagSupport { public void doTag() throws JspException, IOException { getJspContext().getOut().write("Hello, world."); }}Tag Handlers for Tags with AttributesThis section describes how to define attributes for a tag handler and howto validate attribute values. Defining Attributes in a Tag HandlerFor each tag attribute, you must define a set method in the taghandler that conforms to the JavaBeans architecture conventions. For example, consider the taghandler for the JSTLc:if tag: <c:if test="${Clear}">This tag handler contains the following method: public void setTest(boolean test) { this.test = test;}As shown by the preceding example, the name of the attribute mustmatch the name of the set method. Attribute ValidationThe documentation for a tag library should describe valid values for tag attributes.When a JSP page is translated, a web container will enforce any constraintscontained in the TLD element for each attribute. The attributes passed to a tag can also be validated at translation timeusing thevalidate method of a class derived fromTagExtraInfo. This class isalso used to provide information about variables defined by the tag (seeTagExtraInfo Class). Thevalidate method is passed the attribute information in aTagData object, whichcontains attribute-value tuples for each of the tag’s attributes. Because the validation occurs attranslation time, the value of an attribute that is computed at request timewill be set toTagData.REQUEST_TIME_VALUE. The tag<tt:twa attr1="value1"/> has the following TLDattribute element: <attribute> <name>attr1</name> <required>true</required> <rtexprvalue>true</rtexprvalue></attribute> This declaration indicates that the value ofattr1 can be determined at runtime. The followingvalidate method checks whether the value ofattr1 is a validBoolean value. Note that because the value ofattr1 can be computed atruntime,validate must check whether the tag user has chosen to providea runtime value. public class TwaTEI extends TagExtraInfo { public ValidationMessage[] validate(TagData data) { Object o = data.getAttribute("attr1"); if (o != null && o != TagData.REQUEST_TIME_VALUE) { if (((String)o).toLowerCase().equals("true") || ((String)o).toLowerCase().equals("false") ) return null; else return new ValidationMessage(data.getId(), "Invalid boolean value."); } else return null; }}Setting Dynamic AttributesSimple tag handlers that support dynamic attributes must declare that they do so inthetag element of the TLD (seeDeclaring Tag Handlers). In addition, your taghandler must implement thesetDynamicAttribute method of theDynamicAttributes interface. For each attributespecified in the tag invocation that does not have a correspondingattributeelement in the TLD, the web container callssetDynamicAttribute, passing in thenamespace of the attribute (ornull if in the default namespace), the nameof the attribute, and the value of the attribute. You must implement thesetDynamicAttribute method to remember the names and values of the dynamic attributes sothat they can be used later whendoTag is executed. If thesetDynamicAttributemethod throws an exception, thedoTag method is not invoked for the tag,and the exception must be treated in the same manner as if itcame from an attribute setter method. The following implementation ofsetDynamicAttribute saves the attribute names and values in lists.Then, in thedoTag method, the names and values are echoed to theresponse in an HTML list. private ArrayList keys = new ArrayList();private ArrayList values = new ArrayList();public void setDynamicAttribute(String uri, String localName, Object value ) throws JspException { keys.add( localName ); values.add( value );}public void doTag() throws JspException, IOException { JspWriter out = getJspContext().getOut(); for( int i = 0; i < keys.size(); i++ ) { String key = (String)keys.get( i ); Object value = values.get( i ); out.println( "<li>" + key + " = " + value + "</li>" ); }}Setting Deferred Value Attributes and Deferred Method AttributesFor each tag attribute that accepts a deferred value expression or a deferredmethod expression, the tag handler must have a method to access the valueof the attribute. The methods that access the value of a deferred value attribute method mustaccept aValueExpression object. The methods that access the value of a deferredmethod attribute must accept aMethodExpression object. These methods take the formsetXXX, whereXXX is the name of the attribute. The following example shows a method that can be used to accessthe value of a deferred value attribute calledattributeName: private javax.el.ValueExpression attributeName = null;public void setAttributeName( javax.el.ValueExpression attributeName) { this.attributeName = attributeName;}Deferred value attributes and deferred method attributes are primarily used by JavaServer Facestechnology. SeeGetting the Attribute Values for an example of creating a tag handler that processesthese attributes for a JavaServer Faces application. If you have an attribute that is both dynamic and deferred (meaning thatthe tag attribute definition accepts a deferred expression and hasrtexprvalue setto true), then thesetX method that accesses this value must accept anObject instance and test if theObject instance is a deferred value expression, asshown in this pseudocode: public void setAttr(Object obj) { if (obj instance of ValueExpression) { // this is a deferred expression else { // this is an rtexpression }}Tag Handlers for Tags with BodiesA simple tag handler for a tag with a body is implemented differentlydepending on whether or not the tag handler needs to manipulate the body.A tag handler manipulates the body when it reads or modifies the contentsof the body. Tag Handler Does Not Manipulate the BodyIf a tag handler needs simply to evaluate the body, it getsthe body using thegetJspBody method ofSimpleTag and then evaluates the body usingtheinvoke method. The following tag handler accepts atest parameter and evaluates the body ofthe tag if the test evaluates totrue. The body of the tagis encapsulated in a JSP fragment. If the test istrue, thehandler retrieves the fragment using thegetJspBody method. Theinvoke method directs alloutput to a supplied writer or, if the writer isnull, to theJspWriter returned by thegetOut method of theJspContext associated with the tag handler. public class IfSimpleTag extends SimpleTagSupport { private boolean test; public void setTest(boolean test) { this.test = test; } public void doTag() throws JspException, IOException { if(test){ getJspBody().invoke(null); } }}Tag Handler Manipulates the BodyIf the tag handler needs to manipulate the body, the tag handlermust capture the body in aStringWriter. Theinvoke method directs all output toa supplied writer. Then the modified body is written to theJspWriter returnedby thegetOut method of theJspContext. Thus, a tag that converts itsbody to uppercase could be written as follows: public class SimpleWriter extends SimpleTagSupport { public void doTag() throws JspException, IOException { StringWriter sw = new StringWriter(); jspBody.invoke(sw); jspContext(). getOut().println(sw.toString().toUpperCase()); }}Tag Handlers for Tags That Define VariablesSimilar communication mechanisms exist for communication between JSP page and tag handlers asfor JSP pages and tag files. To emulateIN parameters, use tag attributes. A tag attribute is communicated betweenthe calling page and the tag handler when the tag is invoked. Nofurther communication occurs between the calling page and the tag handler. To emulateOUT or nested parameters, use variables with availabilityAT_BEGIN,AT_END, orNESTED.The variable is not initialized by the calling page but instead is setby the tag handler. ForAT_BEGIN availability, the variable is available in the calling page from thestart tag until the scope of any enclosing tag. If there’s no enclosingtag, then the variable is available to the end of the page. ForAT_END availability, the variable is available in the calling page after the endtag until the scope of any enclosing tag. If there’s no enclosing tag,then the variable is available to the end of the page. For nestedparameters, the variable is available in the calling page between the start tagand the end tag. When you develop a tag handler you are responsible for creating and settingthe object referenced by the variable into a context that is accessible fromthe page. You do this by using theJspContext().setAttribute(name, value) orJspContext.setAttribute(name,value,scope) method. You retrievethe page context using thegetJspContext method ofSimpleTag. Typically, an attribute passed to the custom tag specifies the name of thevariable and the value of the variable is dependent on another attribute. Forexample, theiterator tag introduced inChapter 5, JavaServer Pages Technology retrieves the name of the variablefrom thevar attribute and determines the value of the variable from acomputation performed on thegroup attribute. public void doTag() throws JspException, IOException { if (iterator == null) return; while (iterator.hasNext()) { getJspContext().setAttribute(var, iterator.next()); getJspBody().invoke(null); }}public void setVar(String var) { this.var = var;}public void setGroup(Collection group) { this.group = group; if(group.size() > 0) iterator = group.iterator();}The scope that a variable can have is summarized inTable 8-13. Thescope constrains the accessibility and lifetime of the object. Table 8-13 Scope of Objects
TagExtraInfo ClassDeclaring Tag Variables for Tag Handlers discussed how to provide information about tag variables in the tag librarydescriptor. This section describes another approach: defining a tag extra info class. You definea tag extra info class by extending the classjavax.servlet.jsp.tagext.TagExtraInfo. ATagExtraInfomust implement thegetVariableInfo method to return an array ofVariableInfo objects containingthe following information:
The web container passes a parameter of typejavax.servlet.jsp.tagext.TagData to thegetVariableInfo method,which contains attribute-value tuples for each of the tag’s attributes. These attributes can beused to provide theVariableInfo object with an EL variable’s name and class. The following example demonstrates how to provide information about the variable created bytheiterator tag in a tag extra info class. Because the name (var)and class (type) of the variable are passed in as tag attributes, theycan be retrieved using thedata.getAttributeString method and can be used to fill intheVariableInfo constructor. To allow the variablevar to be used onlywithin the tag body, you set the scope of the object toNESTED. package iterator;public class IteratorTEI extends TagExtraInfo { public VariableInfo[] getVariableInfo(TagData data) { String type = data.getAttributeString("type"); if (type == null) type = "java.lang.Object"; return new VariableInfo[] { new VariableInfo(data.getAttributeString("var"), type, true, VariableInfo.NESTED) }; }}The fully qualified name of the tag extra info class defined foran EL variable must be declared in the TLD in thetei-class subelement ofthetag element. Thus, thetei-class element forIteratorTei would be as follows: <tei-class> iterator.IteratorTEI</tei-class> Cooperating TagsTags cooperate by sharing objects. JSP technology supports two styles of object sharing. The first style requires that a shared object be named and stored inthe page context (one of the implicit objects accessible to JSP pages aswell as tag handlers). To access objects created and named by another tag,a tag handler uses thepageContext.getAttribute(name,scope) method. In the second style of object sharing, an object created by the enclosingtag handler of a group of nested tags is available to all innertag handlers. This form of object sharing has the advantage that it usesa private namespace for the objects, thus reducing the potential for naming conflicts. To access an object created by an enclosing tag, a tag handler mustfirst obtain its enclosing tag by using the static methodSimpleTagSupport.findAncestorWithClass(from,class) ortheSimpleTagSupport.getParent method. The former method should be used when a specific nestingof tag handlers cannot be guaranteed. After the ancestor has been retrieved, atag handler can access any statically or dynamically created objects. Statically created objects aremembers of the parent. Private objects can also be created dynamically. Such privatelynamed objects would have to be managed by the tag handler; one approachwould be to use aMap to store name-object pairs. The following example illustrates a tag handler that supports both the named approachand the private object approach to sharing objects. In the example, the handlerfor a query tag checks whether an attribute namedconnectionId has beenset. If theconnectionId attribute has been set, the handler retrieves the connectionobject from the page context. Otherwise, the tag handler first retrieves the taghandler for the enclosing tag and then retrieves the connection object from thathandler. public class QueryTag extends SimpleTagSupport { public int doTag() throws JspException { String cid = getConnectionId(); Connection connection; if (cid != null) { // there is a connection id, use it connection =(Connection)pageContext. getAttribute(cid); } else { ConnectionTag ancestorTag = (ConnectionTag)findAncestorWithClass(this, ConnectionTag.class); if (ancestorTag == null) { throw new JspTagException("A query without a connection attribute must be nested within a connection tag."); } connection = ancestorTag.getConnection(); ... } }}The query tag implemented by this tag handler can be used ineither of the following ways: <tt:connection cid="con01" ... > ... </tt:connection><tt:query connectionId="con01"> SELECT account, balance FROM acct_table where customer_number = ? <tt:param value="${requestScope.custNumber}" /></tt:query><tt:connection ... > <tt:query cid="balances"> SELECT account, balance FROM acct_table where customer_number = ? <tt:param value="${requestScope.custNumber}" /> </tt:query></tt:connection>The TLD for the tag handler uses the following declaration to indicate thattheconnectionId attribute is optional: <tag> ... <attribute> <name>connectionId</name> <required>false</required> </attribute></tag> Tag Handler ExamplesThe simple tags described in this section demonstrate solutions to two recurring problemsin developing JSP applications: minimizing the amount of Java programming in JSP pagesand ensuring a common look and feel across applications. In doing so, theyillustrate many of the styles of tags discussed in the first part ofthe chapter. An Iteration TagConstructing page content that is dependent on dynamically generated data often requires theuse of flow control scripting statements. By moving the flow control logic totag handlers, flow control tags reduce the amount of scripting needed in JSPpages. Iteration is a very common flow control function and is easily handledby a custom tag. The discussion on using tag libraries inChapter 5, JavaServer Pages Technology introduced a tag librarycontaining aniterator tag. The tag retrieves objects from a collection stored ina JavaBeans component and assigns them to an EL variable. The bodyof the tag retrieves information from the variable. As long as elements remainin the collection, theiterator tag causes the body to be reevaluated. The tagin this example is simplified to make it easy to demonstrate how toprogram a custom tag. web applications requiring such functionality should use the JSTLforEach tag, which is discussed inIterator Tags. JSP PageTheindex.jsp page invokes theiterator tag to iterate through a collection ofdepartment names. Each item in the collection is assigned to thedepartmentName variable. <%@ taglib uri="/tlt" prefix="tlt" %><html> <head> <title>Departments</title> </head> <body bgcolor="white"> <jsp:useBean/> <table border=2 cellspacing=3 cellpadding=3> <tr> <td><b>Departments</b></td> </tr> <tlt:iterator var="departmentName" type="java.lang.String" group="${myorg.departmentNames}"> <tr> <td><a href="list.jsp?deptName=${departmentName}"> ${departmentName}</a></td> </tr> </tlt:iterator> </table> </body></html>Tag HandlerThe collection is set in the tag handler by means of thegroup attribute. The tag handler retrieves an element from the group and passesthe element back to the page in the EL variable whose name isdetermined by thevar attribute. The variable is accessed in the calling pageusing the JSP expression language. After the variable is set, the tag bodyis evaluated with theinvoke method. public void doTag() throws JspException, IOException { if (iterator == null) return; while (iterator.hasNext()) { getJspContext().setAttribute(var, iterator.next()); getJspBody().invoke(null); }}public void setVar(String var) { this.var = var;}public void setGroup(Collection group) { this.group = group; if(group.size() > 0) iterator = group.iterator();}A Template Tag LibraryA template provides a way to separate the common elements that arepart of each screen from the elements that change with each screen ofan application. Putting all the common elements together into one file makes iteasier to maintain and enforce a consistent look and feel in all thescreens. It also makes development of individual screens easier because the designer canfocus on portions of a screen that are specific to that screen whilethe template takes care of the common portions. The template is a JSP page that has placeholders for the partsthat need to change with each screen. Each of these placeholders is referredto as aparameter of the template. For example, a simple template might includea title parameter for the top of the generated screen and a bodyparameter to refer to a JSP page for the custom content ofthe screen. The template uses a set of nested tags (definition,screen, andparameter)to define a table of screen definitions and uses aninsert tag toinsert parameters from a screen definition into a specific application screen. JSP PagesThe template for the Duke’s Bookstore example,tut-install/javaeetutorial5/examples/web/bookstore3/web/template/template.jsp, is shown next. Thispage includes a JSP page that creates the screen definition and then usestheinsert tag to insert parameters from the definition into the application screen. <%@ taglib uri="/tutorial-template" prefix="tt" %><%@ page errorPage="/template/errorinclude.jsp" %><%@ include file="/template/screendefinitions.jsp" %><html><head><title><tt:insert definition="bookstore" parameter="title"/></title></head><body bgcolor="#FFFFFF"> <tt:insert definition="bookstore" parameter="banner"/><tt:insert definition="bookstore" parameter="body"/><center><em>Copyright © 2004 Sun Microsystems, Inc. </em></center></body></html> Thetut-install/javaeetutorial5/examples/web/bookstore3/web/template/screendefinitions.jspf page creates a definition for the screen specified by therequest attributejavax.servlet.forward.servlet_path: <tt:definition name="bookstore"screen="${requestScope [’javax.servlet.forward.servlet_path’]}"> <tt:screen> <tt:parameter name="title" value="Duke’s Bookstore" direct="true"/> <tt:parameter name="banner" value="/template/banner.jsp" direct="false"/> <tt:parameter name="body" value="/bookstore.jsp" direct="false"/> </tt:screen> <tt:screen> <tt:parameter name="title" direct="true"> <jsp:attribute name="value" > <fmt:message key="TitleBookCatalog"/> </jsp:attribute> </tt:parameter> <tt:parameter name="banner" value="/template/banner.jsp" direct="false"/> <tt:parameter name="body" value="/bookcatalog.jsp" direct="false"/> </tt:screen> ...</tt:definition>The template is instantiated by theDispatcher servlet.Dispatcher first gets therequested screen.Dispatcher performs business logic and updates model objects based on therequested screen. For example, if the requested screen is/bookcatalog,Dispatcher determines whethera book is being added to the cart based on the value ofthe Add request parameter. It sets the price of the book ifit’s on sale, and then adds the book to the cart. Finally, theservlet dispatches the request totemplate.jsp: public class Dispatcher extends HttpServlet { @Resource UserTransaction utx; public void doGet(HttpServletRequest request, HttpServletResponse response) { String bookId = null; Book book = null; String clear = null; BookDBAO bookDBAO = (BookDBAO)getServletContext(). getAttribute("bookDBAO"); HttpSession session = request.getSession(); String selectedScreen = request.getServletPath(); ShoppingCart cart = (ShoppingCart)session. getAttribute("cart"); if (cart == null) { cart = new ShoppingCart(); session.setAttribute("cart", cart); } if (selectedScreen.equals("/bookcatalog")) { bookId = request.getParameter("Add"); if (!bookId.equals("")) { try { book = bookDBAO.getBook(bookId); if ( book.getOnSale() ) { double sale = book.getPrice() * .85; Float salePrice = new Float(sale); book.setPrice(salePrice.floatValue()); } cart.add(bookId, book); } catch (BookNotFoundException ex) { // not possible } } } else if (selectedScreen.equals("/bookshowcart")) { bookId =request.getParameter("Remove"); if (bookId != null) { cart.remove(bookId); } clear = request.getParameter("Clear"); if (clear != null && clear.equals("clear")) { cart.clear(); } } else if (selectedScreen.equals("/bookreceipt")) { // Update the inventory try { utx.begin(); bookDBAO.buyBooks(cart); utx.commit(); } catch (Exception ex) { try { utx.rollback(); request.getRequestDispatcher( "/bookordererror.jsp"). forward(request, response); } catch(Exception e) { System.out.println( "Rollback failed: "+e.getMessage()); e.printStackTrace(); } } } try { request. getRequestDispatcher( "/template/template.jsp"). forward(request, response); } catch(Exception ex) { ex.printStackTrace(); } } public void doPost(HttpServletRequest request, HttpServletResponse response) { request.setAttribute("selectedScreen", request.getServletPath()); try { request. getRequestDispatcher( "/template/template.jsp"). forward(request, response); } catch(Exception ex) { ex.printStackTrace(); } }}Tag HandlersThe template tag library contains four tag handlers (DefinitionTag,ScreenTag,ParameterTag, andInsertTag)that demonstrate the use of cooperating tags.DefinitionTag,ScreenTag, andParameterTag constitute aset of nested tag handlers that share private objects.DefinitionTag creates a publicobject namedbookstore that is used byInsertTag. IndoTag,tut-install/javaeetutorial5/examples/web/bookstore3/src/java/com/sun/bookstore3/template/DefinitionTag.java creates a private object namedscreens that contains a hashtable of screen definitions. A screen definition consists of a screen identifier anda set of parameters associated with the screen. These parameters are loaded whenthe body of the definition tag, which contains nestedscreen andparameter tags,is invoked.DefinitionTag creates a public object of classtut-install/javaeetutorial5/examples/web/bookstore3/src/java/com/sun/bookstore3/template/Definition.java, selects a screendefinition from thescreens object based on the URL passed in the request,and uses this screen definition to initialize a publicDefinition object. public int doTag() { try { screens = new HashMap(); getJspBody().invoke(null); Definition definition = new Definition(); PageContext context = (PageContext)getJspContext(); ArrayList params = (ArrayList) screens.get(screenId); Iterator ir = null; if (params != null) { ir = params.iterator(); while (ir.hasNext()) definition.setParam((Parameter)ir.next()); // put the definition in the page context context.setAttribute(definitionName, definition, context.APPLICATION_SCOPE); } }The table of screen definitions is filled in byScreenTag andParameterTagfrom text provided as attributes to these tags.Table 8-14 shows the contentsof the screen definitions hash table for the Duke’s Bookstore application. Table 8-14 Screen Definitions
If the URL passed in the request is/bookstore, theDefinition objectcontains the items from the first row ofTable 8-14 (seeTable 8-15). Table 8-15 Definition Object Contents for URL/bookstore
The parameters for the URL/bookstore are shown inTable 8-16. The parametersspecify that the value of thetitle parameter,Duke’s Bookstore, should be inserted directlyinto the output stream, but the values ofbanner andbody should be includeddynamically. Table 8-16 Parameters for the URL/bookstore
tut-install/javaeetutorial5/examples/web/bookstore3/src/java/com/sun/bookstore3/template/InsertTag.java inserts parameters of the screen definition into the response. ThedoTag methodretrieves the definition object from the page context and then inserts the parametervalue. If the parameter is direct, it is directly inserted into the response;otherwise, the request is sent to the parameter, and the response is dynamicallyincluded into the overall response. public void doTag() throws JspTagException { Definition definition = null; Parameter parameter = null; boolean directInclude = false; PageContext context = (PageContext)getJspContext(); // get the definition from the page context definition = (Definition)context.getAttribute( definitionName, context.APPLICATION_SCOPE); // get the parameter if (parameterName != null && definition != null) parameter = (Parameter) definition.getParam(parameterName); if (parameter != null) directInclude = parameter.isDirect(); try { // if parameter is direct, print to out if (directInclude && parameter != null) context.getOut().print(parameter.getValue()); // if parameter is indirect, include results of dispatching to page else { if ((parameter != null) && (parameter.getValue() != null)) context.include(parameter.getValue()); } } catch (Exception ex) { throw new JspTagException(ex.getMessage()); }}Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices |