Your Federal Quarterly Tax Payments are due April 15th Get Help Now >>

JSP 2.0 (in J2EE 1.4) by bzs12927

VIEWS: 10 PAGES: 48

									08/02/2006




             JSP 2.0 (in J2EE 1.4)


                                     1
08/02/2006




             Disclaimer & Acknowledgments
             ?   Even though Sang Shin is a full-time employees of Sun
                 Microsystems, the contents here are created as his own personal
                 endeavor and thus does not reflect any official stance of Sun
                 Microsystems.
             ?   Sun Microsystems is not responsible for any inaccuracies in the
                 contents.
             ?   Acknowledgements
                  – Many slides are borrowed from “Servlet 2.4 and JSP 2.0
                    specification” JavaOne 2003 presentation by Mark Roth of Sun
                    Microsystems
                  – The slides, speaker notes, and example code of this
                    presentation are created from
                      ? “Custom Tags” section of Java WSDP 1.2 tutorial written by

                        Stephanie Bodoff of Sun Microsystems

                                                                                     2
08/02/2006




             Revision History
             ?   10/13/2003: version 1: created by Sang Shin
             ?   Things to do
                 –   Speaker notes still need to be added and polished
                 –   Some concepts still need to be better explained




                                                                         3
08/02/2006




                      Agenda
                       ?   Focus of JSP 2.0 technology
                       ?   New features in JSP 2.0
                           –   Expression Language (EL)
                           –   Simple tag extensions
                           –   Tag files
                           –   Improved XML syntax
                           –   Other features




                                                                           4




             So this is the agenda. First I will spend some time talking about
             focus of JSP 2.0. And the rest of this presentation will be
             devoted to talking about newly added features of JSP 2.0. As
             you will see later on, the newly added features of JSP 2.0 are
             rather significant.
08/02/2006




                                Focus of JSP 2.0 Technology
                                  ?     Ease of use – lowers the bar

                                         User Class               HTML     XML      Java
                              JSP 2.0




                                         Tag Library Developer
                    JSP 1.2




                                         Advanced Page Author

                                         Basic Page Author


                                              = Basic Knowledge          = Expert
                                                                                           5



             The focus of JSP 2.0 is ease of use.

             Web-tier developers can be categorized into 3 groups - tag library
             developer who has be fluent in HTML, XML, and Java technology. And
             then we have advanced page author who might not be a Java developer
             but should be familiar with HTML and XML. Then there are basic page
             authors whose primary skillset is HTML.

             JSP 1.2 targets the first 2 tier groups while JSP 2.0 lowers the bar so that
             the third tier group, basic page authors can design the JSP page based
             Web tier applications.

             So what features of JSP 2.0 will make this happen?
08/02/2006




                   JSP 1.2 Syntax With Scriptlets
                  <%-- Output Shopping Cart --%>
                  <%@ page import ="com.acme.util.*" %>
                  <%@ taglib prefix="util" uri="http://mytaglib" %>

                  <html>
                    <body>
                      <util:getShoppingCart var="cart" />
                       <table>
                       <% for( int i = 0; i < cart.size(); i++ ) {
                             CartItem item=(CartItem)cart.get(i);
                      %>
                          <tr>
                             <td><%= item.getName() %></td>
                             <td><%= item.getPrice() %> </td>
                          </tr>
                       <% } %>
                       </table>
                    </body>
                  </html>
                                                                            6


             This slide shows a JSP page in which the logic of displaying
             lineitems of a shopping cart is written using the JSP 1.2 syntax
             with scriptlets. And as you can see, the page is rather hard to
             build and read. Now let's see how this page can be simplified
             using JSP 2.0 syntax in the following slide.
08/02/2006




                  JSP 2.0 Syntax Without Scriptlets
                  <%-- Output Shopping Cart --%>
                  <%@ taglib prefix="util" uri="http://mytaglib" %>
                  <%@ taglib prefix="c"
                         uri="http://java.sun.com/jsp/jstl/core" %>
                  <html>
                    <body>
                       <util:getShoppingCart var="cart" />
                       <table>
                         <c:forEach var="item" values="${cart}">
                            <tr>
                               <td>${item.name}</td>
                               <td>${item.price}</td>
                            </tr>
                         </c:forEach>
                      </table>
                    </body>
                  </html>

                                                                            7


             This slide shows JSP page which contains same display logic but
             using JSP 2.0 expression language syntax. For example, the
             shopping cart object is represented as ${cart} while the name
             and price of each line item in the shopping cart is represented as
             ${item.name} and ${item.price} respectively.
08/02/2006




                 JSP 2.0 Improved XML Syntax
                  <!-- Output Shopping Cart -->
                  <html xmlns:util="http://mytaglib"
                       xmlns:c="http://java.sun.com/jsp/jstl/core">
                    <body>
                       <util:getShoppingCart var="cart" />
                       <table>
                          <c:forEach var="item" values="${cart}">
                            <tr>
                               <td>${item.name}</td>
                               <td>${item.price}</td>
                            </tr>
                          </c:forEach>
                       </table>
                    </body>
                  </html>



                                                                      8


             This slide shows the same JSP 2.0 based page but using XML
             syntax even for the directives. One reason you might want to
             build your JSP page as XML document is to be able to use XML
             schema for validation and to allow XML tools to be used for
             building and manipulating the JSP page.
08/02/2006




                        Expression Language

                                                                                9




             The first major enhancement in JSP 2.0 is integration of Expression
             Language (EL) as a built-in feature of JSP. Expression Language has been
             around as part of Java Standard Tag Library (JSTL) 1.0. Now due to its
             huge success, EL is now part of JSP itself. That is, Servlet 2.4 and JSP 2.0
             compatible container should be able to handle EL expressions as native
             JSP syntax.
08/02/2006




                      Expression Language
                       ?   Based on “SPEL” from JSTL 1.0
                           –   Simplest Possible Expression Language
                       ?   Let you access the property values of a
                           JavaBean in a simpler syntax
                           –   Example: ${item.price}
                       ?   Recognized by JSP container in:
                           –   Template text
                           –   Attributes of any standard or custom action
                       ?   Support for custom EL functions:
                           –   Extensible via tag libraries
                           –   Example: ${fn:allCaps(lastName)}
                           –   JSTL 1.1 provides 16 standard EL functions
                                                                                10



             Expression language is based on “Simplest Possible Expression
             Language” from JSTL 1.0. It basically let you access the property values
             of a JavaBean in a simpler syntax. For example, “price” property value of
             “item” object can be displayed by using ${item.price} syntax. It also let
             you perform arithmetic operations, comparisons. You can also access the
             implicit objects such as form input parameters from the HTML client.

             The JSP expression language allows you to define a function that can be
             invoked in an expression. If you are familiar with string manipulation
             code, the functions serve somewhat similar purpose. The difference is that
             under JSP 2.0, these functions can be invoked using EL syntax.

             Functions are defined using the same mechanisms as custom tags. For
             example, if there is a function, for example, allCaps() method that is
             defined inside tag handler, you can call it through EL syntax, for example,
             “fn” prefix with the method name and parameter.
08/02/2006




                      Integrated Expression
                      Language Example
                      ?   Using scriptlets:
                          <center>
                            <jsp:useBean id="foo" class="FooBean" />
                            <%= foo.getBar() %>
                          </center>



                      ?   Equivalent, using an EL expression:
                          <center>
                            ${foo.bar}
                          </center>

                                                                               11




             So this is a very simple comparison between JSP page that uses
             scriptlet and the one that uses expression languagedoing the
             same thing.

             In the upper part of the slide, we use scriptlet in order to retrieve
             the value of a property called Bar from a JavaBean called foo.
             So here you declare your JavaBean, foo, first and the use getter
             method, getBar(), to retrieve the value.

             In the bottom part of the slide, we use EL expression to do the
             same thing. So in order to get the value of bar property of the
             foo object, you just say ${foo.bar}.
08/02/2006




                     Integrated Expression
                     Language Example
                     ?   Using scriptlets:
                         <% Map m = (Map)pageContext.getAttribute("state" );
                           State s = ((State)m.get( "NY" ));
                           if( s != null ) {
                         %>
                              <%= s.getCapitol() %>
                         <% } %>

                     ?   Equivalent, using an EL expression:
                         ${state["NY"].capitol}


                                                                               12



             This is another example expression language, this time with a
             Map collection object in which multiple key-object pairs, in this
             case, state and its capital city pairs, are stored.

             Again, if you want to get the capital city of a particular state
             from states map object, you provide the key value with a bracket
             and the access the capital property.
08/02/2006




                      Simple Tag Handlers &
                           Extensions

                                                                              13




             Now let's talk about simple tag handlers and extensions, which is one of
             the significant enhancements in JSP 2.0.
08/02/2006




                  Comparison of Tag Extensions
                   ?   Classic tag extensions (JSP 1.2 technology)
                       –   Complex tag handler API
                       –   Written only in the Java programming language
                       –   Created only by tag library developers
                   ?   Simple tag extensions & Tag Files (JSP 2.0
                       technology)
                       –   Simpler tag handler API
                       –   Written in the Java programming language or using
                           JSP syntax
                       –   Created by page authors or tag library developers

                                                                               14



             I already mentioned that using simple tag handler is much
                simpler to use than classic tag handler. It is expected all newly
                written tag libraries are written using simple tag handler. So
                let's compare the two here.

             Now in terms of creating tag extensions, in JSP 1.2, as we will
              see later on, tag handlers can be written only in Java
              programming language by only Java programmers. In JSP 2.0,
              besides leveraging simpler tag handler API, the tag handlers
              can be in the form of JSP syntax (these are *.tag files), which
              means page authors can also create tag extensions.
08/02/2006




                          Simple Tag Handlers
                          ?   Simpler to use than classic tag handlers
                          ?   Implement SimpleTag interface
                          ?   Usually extend SimpleTagSupport class
                          ?   doTag() of SimpleTag interface gets invoked
                              when the end element of the tag is
                              encountered
                              –   You want to override this method




                                                                                  15




             Why do you want to use simple tag handlers as opposed to classic tag handlers?
             Simple tag handlers are much simpler to use than the classic tag handlers.

             The classes and interfaces used to implement simple tag handlers are contained in
             the javax.servlet.jsp.tagext package. Simple tag handlers implement the
             SimpleTag interface. Interfaces can be used to take an existing Java object and
             make it a tag handler. For most newly created handlers, you would use the
             SimpleTagSupport classes as a base class.

             The heart of a simple tag handler is a single method--doTag() method--which gets
             invoked when the end element of the tag is encountered. Note that the default
             implementation of the doTag method() of SimpleTagSupport does nothing. And
             you want to override this doTag() method most of the time.
08/02/2006




                  How is a Simple Tag Handler
                  called from container?
                   ATag t = new ATag();
                   t.setJSPContext(...);
                   t.setParent(...);
                   t.setAttribute1(value1);
                   t.setAttribute2(value2);
                   ...
                   t.setJspBody(new JspFragment(...))
                   t.doTag();


                                                                           16




             The SimpleTag interface defines the basic protocol between a
             simple tag handler and servlet container. The servlet container
             invokes the setJspContext(), setParent(), and attribute setting
             methods() before setting JspFragment and then calling doTag()
             method. (sang: I need to explain this better.)

             ATag t = new ATag();
             t.setJSPContext(...);
             t.setParent(...);
             t.setAttribute1(value1);
             t.setAttribute2(value2);
             ...
             t.setJspBody(new JspFragment(...))
             t.doTag();
08/02/2006




                        JspFragment interface
                         ?   Encapsulates a portion of JSP code in an
                             object that can be invoked as many times as
                             needed
                         ?   JSP Fragments are defined using JSP
                             syntax
                             –   as the body of a tag for an invocation to a
                                 SimpleTag handler, or
                             –   as the body of a <jsp:attribute> standard action
                                 specifying the value of an attribute that is declared
                                 as a fragment, or
                             –   to be of type JspFragment in the TLD
                                                                                         17




             JspFragment object encapsulates a portion of JSP code in an object that can be
             invoked as many times as needed. JSP Fragments are defined using JSP syntax
             as the body of a tag for an invocation to a SimpleTag handler, or as the body of
             a <jsp:attribute> standard action specifying the value of an attribute that is
             declared as a fragment, or to be of type JspFragment in the TLD.

             The definition of the JSP fragment must only contain template text and JSP
             action elements. In other words, it must not contain scriptlets or scriptlet
             expressions. At translation time, the container generates an implementation of
             the JspFragment interface capable of executing the defined fragment.

             A tag handler can invoke the fragment zero or more times, or pass it along to
             other tags, before returning. To communicate values to/from a JSP fragment,
             tag handlers store/retrieve values in the JspContext associated with the
             fragment.

             Note that tag library developers and page authors should not generate
             JspFragment implementations manually.
08/02/2006




                         Simple Tag handler that does not
                         manipulate body
                         ?   If a tag handler needs to simply evaluate the
                             body,
                             –   it gets the body with the getJspBody () method of
                                 SimpleTag in the form of JspFragment object
                             –   and then evaluates the body with the invoke()
                                 method
                         ?   Invoke() method
                             –   use invoke(null) when there is no need to
                                 manipualte body
                             –   use invoke(StringWriter writer) otherwise

                                                                                      18




             If a tag handler needs to simply evaluate the body, that is,if it just spits out the
             body contents without modifying it, the handler gets the body with the
             getJspBody method of SimpleTag interface and then evaluates the body with
             the invoke method. (Sang: Add more explanation on evaluation.)
08/02/2006




                         Example: Simple Tag handler that
                         does not manipulate body
                         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);
                             }
                           }
                         }




                                                                                     19




             The tag handlerin the slide accepts a test parameter and evaluates the body of
             the tag if the test evaluates to true. The body of the tag is encapsulated in a JSP
             fragment. If the test is true, the handler retrieves the fragment with the
             getJspBody method. The invoke method directs all output to a supplied writer
             or to the JspWriter returned by the getOut method of the JspContext associated
             with the tag handler if the writer is null.

             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);
                }
               }
             }
08/02/2006




                        Simple Tag handler that does
                        manipulate body
                         ?   If the tag handler needs to manipulate the
                             body, the tag handler must capture the body
                             in a StringWriter
                             public class SimpleWriter extends SimpleTagSupport {
                               public void doTag() throws JspException, IOException {
                                 StringWriter sw = new StringWriter();
                                 jspBody.invoke(sw);
                                 jspContext().getOut().println(sw.toString().toUpperCase());
                               }
                             }




                                                                                               20




             If the tag handler needs to manipulate the body, the tag handler must capture the
             body in a StringWriter. The invoke method directs all output to a supplied
             writer. Then the modified body is written to the JspWriter returned by the
             getOut method of the JspContext. Thus, a tag that converts its body to upper
             case 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());
               }
             }
08/02/2006




                                  Repeat Tag Implemented as a
                                  Classic JSP 1.2 Tag Extension
                                 <%@ taglib prefix="my"
                                       uri="/mytags" %>                       Tag
                                 <my:repeat num="3">
                Usage




                                   tag body
                                 </my:repeat>                       BodyTag     IterationTag

                                                                                TagSupport
                                 int doStartTag() {
                                    this.count = this.num;      b     BodyTagSupport
                Implementation




                                    return Tag.EVAL_BODY_INCLUDE;
                                 }                                     RepeatHandler     a

                                 int doAfterBody() {                    setNum()
                                    this.count--;           c           doStartTag()
                                    return (this.count > 0) ?           doInitBody()
                                     Tag.EVAL_BODY_AGAIN :              doAfterBody()
                                     Tag.SKIP_BODY;             d       doEndTag()
                                 }
                                                                                             21



             So let me compare the repeat tag implementation that uses
             classic JSP 1.2 tag handler on this slide again the one that uses
             JSP 2.0 simple tag handler on the following slide.

             As the picture of the right side of this slide shows,
             RepeatHandler tag handler implements several methods
             including, setNum(), doStartTag(), doInitBody(), doAfterBody(),
             and doEndTag() method. The RepeatHandler extends the base
             class called BodyTagSupport class, which itself is a
             implementation of BodyTag interface and extension of
             TagSupport class.

             The left upper side of the slide shows the calling JSP page. Here
             the value of an attribute called num is set to3, which is passed to
             the taghandler in the form of setNum() method. Since we are
             evaluating the body content, thedoStartTag() method returns
             EVAL_BODY_INCLUDE indicating the body needs to be
             included for evaluation and the doAfterBody() method gets
             called and depending on count value, it will return
             EVAL_BODY_AGAIN or SKIP_BODY.
08/02/2006




                                 Repeat Tag Implemented as a
                                 Simple JSP 2.0 Tag Extension
                                 <%@ taglib prefix="my"                  SimpleTag
                Usage



                                       uri="/mytags" %>
                                 <my:repeat num="3">                  SimpleTagSupport
                                   tag body
                                 </my:repeat>
                                                                       RepeatHandler
                                                                          setNum()
                                                                          doTag()
                                 void doTag() {
                Implementation




                                   for( int i = 0; i < num; i++ ) {
                                     getJspBody().invoke( null );
                                   }
                                 }




                                                                                         22


             This slide shows repeat tag implementation using Simple Tag
             handler of JSP 2.0. Here the RepeatHandler simply extends
             SimpleTagSupport class , which itself is an implementation of
             SimpleTag interface.

             Now using simple tag handler, all you have to implement is
             doTag() method in which you JspFragment object by calling
             getJspBody() method and then invoke(null) method in order to
             spit out the JspFragment to the output writer.
08/02/2006




                                     Tag Files


                                                                        23




             Tag files is another significant improvement of JSP 2.0.
08/02/2006




                    Tag Files
                     ?   A source file that contains a fragment of
                         JSP code that is reusable as a custom tag
                     ?   Allow you to create custom tags using JSP
                         syntax
                         –   Empowers page authors
                         –   Faster round-trip development
                     ?   Get translated into a tag handler and then
                         compiled automatically by container
                         –   JSP : Servlet :: Tag File : Tag Handler
                     ?   No TLD file is required
                                                                                24


             What is a tag file? A tag file is a JSP source file that contains a
             fragment of JSP code that is reusable as a custom tag.

             A very important aspect of tag file is that it allows you to create
             custom tags using JSP syntax rather than Java programming
             language. Since tag file can be created using JSP syntax, it can
             be created by page authors, which in turn enables faster
             development of Web application.

             Now the tag file gets translated into a tag handler which is then
             compiled automatically by container in the same way the JSP
             page is gets translated into servlet by the container. In this
             sense, the relationship between Tag file and Tag handler is
             similar to the one between JSP and Servlet.

             One important aspect of tag file is that it does not require the
             presence of Tag Library Descriptor (TLD) file.
08/02/2006




                    Tag Files
                    ?   Simple yet flexible packaging
                        –   Just drop a .tag file in /WEB-INF/tags/
                        –   Implicit tag library automatically generated
                        –   Or, write a .tld for added flexibility
                        –   Or, package in a JAR with a .tld




                                                                             25


             Another important feature of tag file is that it enables simpler
             deployment than class Java tag handler model. That is, in order
             deploy tag files, all you have to do is to drop tag files in /WEB-
             INF/tags directory. The container is then deploy the tag files by
             creating implicit tag library. If more flexible deployment is
             desired, then you can still create TLD file.
08/02/2006




                     Declaring a tag library: tagdir
                     attribute in taglib directive
                      ?   Identifies the location of the tag files
                      ?   Value of it must start with /WEB-INF/tags/
                      ?   Syntax
                          –   <%@ taglib prefix="tt" tagdir=/WEB-INF/tags/dir %>




                                                                                   26




             Tag file concept is introduced in JSP 2.0. Tag file is tag handler
             implementation in JSP syntax as opposed to using Java programming
             language.

             The value of tagdir attribute starts with /WEB-INF/tags as shown in the
             slide above.
08/02/2006




                         Directives Used In a Tag file
                         ?   taglib
                         ?   include
                         ?   tag
                             –   Similar to the JSP page's page directive, but applies
                                 to tag files
                         ?   attribute
                             –   Declares attributes of the custom tag defined in the
                                 tag file
                         ?   variable
                             –   Declares an EL variable exposed by the tag to the
                                 calling page
                                                                                         27



         Directives are used to control aspects of tag file translation to a tag handler, specify
         aspects of the tag, attributes of the tag, and variables exposed by the tag. The following
         slide lists the directives that you can use in tag files.

         “taglib” direc tive is identical to taglib directive (see Declaring Tag Libraries) for JSP
         pages.

         “include” directive is identical to include directive (see Reusing Content in JSP Pages)
         for JSP pages. Note that if the included file contains syntax unsuitable for tag files, a
         translation error will occur.

         “tag” directive is similar to the page directive in a JSP page, but applies to tag files
         instead of JSP pages. Like the page directive, a translation unit can contain more than
         one instance of the tag directive. All the attributes apply to the complete translation
         unit. However, there can be only one occurrence of any attribute/value defined by this
         directive in a given translation unit. With the exception of the import attribute, multiple
         attribute/value (re)definitions result in a translation error.

         “attribute” directive declares attributes of the custom tag defined in the tag file.

         “variable” directive declares an EL variable exposed by the tag to the calling page
08/02/2006




             “attribute” Directive attributes
             ?   description
             ?   name
             ?   required
             ?   rtexprvalue
             ?   type
             ?   fragment (default is false)
                 –   if true, container fixes
                      ?   the rtexprvalue attribute at true
                      ?   the type attribute at javax.servlet.jsp.tagext.JspFragment
                 –   Otherwise, it is a normal attribute to be evaluated by
                     the container prior to being passed to the tag handler28

         .
08/02/2006




                        Example 1: Simple Attribute
                        (shipDate.tag)
                        <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
                        <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
                        <%@ attribute name="shipping" required="true" %>

                        <jsp:useBean id="now" class="java.util.Date" />
                        <jsp:useBean id="shipDate" class="java.util.Date" />
                        <c:choose>
                         <c:when test="${shipping == 'QuickShip'}" >
                           <c:set var="days" value="2" />
                         </c:when>
                         <c:when test="${shipping == 'NormalShip'}">
                           <c:set var="days" value="5" />
                         </c:when>
                         <c:when test="${shipping == 'SaverShip'}">
                           <c:set var="days" value="7" />
                         </c:when>
                        </c:choose>
                        <jsp:setProperty name="shipDate" property="time"
                         value="${now.time + 86400000 * days}" />
                        <fmt:formatDate value="${shipDate}" type="date"
                         dateStyle="full"/>.<br><br>                                        29



         The Duke's Bookstore shipDate tag, defined in shipdate.tag, is a custom tag with a
         simple attribute. The tag generates the date of a book order according to the type of
         shipping requested. The tag determines the number of days until shipment from the
         shipping attribute passed to it by the page bookreceipt.jsp. From the days, the tag
         computes the ship date. It then formats the ship date.
08/02/2006




                        Example 1: Simple Attribute
                        (bookreceipt.jsp - calling page)
                        <%@ taglib prefix="sc" tagdir="/WEB-INF/tags" %>
                        <h3><fmt:message key="ThankYou"/> ${param.cardname}.</h3><br>
                        <fmt:message key="With"/>
                        <em><fmt:message key="${param.shipping}"/></em>,
                        <fmt:message key="ShipDateLC"/>
                        <sc:shipDate shipping="${param.shipping}" />
                        <c:remove var="cart" scope="session" />
                        <c:url var="url" value="/bookstore" />
                        <strong><a href="${url}"><fmt:message
                           key="ContinueShopping"/></a>&nbsp;&nbsp;&nbsp;</strong>




                                                                                        30


         This is bookreceipt.jsp page from which value of shippint attribute is gathered from
         input parameter and then passed to the shipdate.tag.
08/02/2006




                        “variable” Directive
                         ?   Declares EL variables
                         ?   EL variables
                             –   EL variables emulate OUT (from tag file to calling
                                 page) type while Tag attributes emulate IN (from
                                 calling page to tag file) type
                             –   not initialized by the calling page
                             –   set by the tag file




                                                                                      31




         Tag attributes are used to customize tag behavior much like parameters are used to
         customize the behavior of object methods. In fact, using tag attributes and EL variables,
         is it possible to emulate various types of parameters--IN, OUT, and nested.

         To emulate IN parameters, use tag attributes. A tag attribute is communicated between
         the calling page and the tag file when the tag is invoked. No further communication
         occurs between the calling page and tag file.

         To emulate OUT or nested parameters, use EL variables. The variable is not initialized
         by the calling page, but set by the tag file. Each type of parameter is synchronized with
         the calling page at various points according to the scope of the variable. See Variable
         Synchronization for details.

         You declare an EL variable exposed by a tag file with the variable directive. A TLD has
         an analogous variable element
08/02/2006




                        “variable” Directive attributes
                         ?   description
                         ?   name-given|name-from-attribute
                             –   Defines an EL variable to be used in the page
                                 invoking this tag
                         ?   alias
                         ?   variable-class
                         ?   declare
                         ?   scope



                                                                                   32




         “variable” directory can have several attributes of its own.

         name-given: name-from-attribute - Defines an EL variable to be used in the page
         invoking this tag. Either name-given or name-from-attribute must be specified. If name-
         given is specified, the value is the name of the variable. If name-from-attribute is
         specified, the value is the name of an attribute whose (translation-time) value at of the
         start of the tag invocation will give the name of the variable.
08/02/2006




                        Evaluating Fragments passed to
                        Tag Files
                        ?   Web container passes two types of
                            fragments
                            –   fragment attribute
                            –   tag body
                        ?   Fragments are evaluated by tag handler not
                            container
                        ?   Within a tag file,
                            –   use jsp:invoke to evaluate a frament attribute
                            –   use jsp:doBody to evaluate a tag file body

                                                                                   33



         When a tag file is executed, the Web container passes it two types of fragments:
         fragment attributes and the tag body, which is implemented as a fragment. Recall from
         the discussion of fragment attributes that fragments are evaluated by the tag handler as
         opposed to the Web container. Within a tag file, you use the jsp:invoke element to
         evaluate a fragment attribute and the jsp:doBody element to evaluate a tag file body.
08/02/2006




                        Evaluating Fragments passed to
                        Tag Files
                        ?   Web container passes two types of
                            fragments
                            –   fragment attribute
                            –   tag body
                        ?   Fragments are evaluated by tag handler not
                            container
                        ?   Within a tag file,
                            –   use jsp:invoke to evaluate a frament attribute
                            –   use jsp:doBody to evaluate a tag file body

                                                                                   34



         When a tag file is executed, the Web container passes it two types of fragments:
         fragment attributes and the tag body, which is implemented as a fragment. Recall from
         the discussion of fragment attributes that fragments are evaluated by the tag handler as
         opposed to the Web container. Within a tag file, you use the jsp:invoke element to
         evaluate a fragment attribute and the jsp:doBody element to evaluate a tag file body.
08/02/2006




                        Evaluating Fragments passed to
                        Tag Files
                         ?   Result of evaluation
                             –   is sent to the response or
                             –   is stored in an EL variable for later manipulatipn
                                  ?   var: type String
                                  ?   varReader: type java.io.Reader
                             –   scope attribute (optional) indicates the scope of
                                 resulting variable
                                  ?   page (default)
                                  ?   request
                                  ?   session
                                  ?   application
                                                                                      35



         The result of evaluating either type of fragment is sent to the response or stored in an
         EL variable for later manipulation. To store the result of evaluating a fragment to an EL
         variable, you specify the var or varReader attributes. If var is specified, the container
         stores the result in an EL variable of type String with the name specified by var. If
         varReader is specified, the container stores the result in an EL variable of type
         java.io.Reader with the name specified by varReader. The Reader object can then be
         passed to a custom tag for further processing. A translation error occurs if both var and
         varReader are specified.

         An optional scope attribute indicates the scope of the resulting variable. The possible
         values are page (default), request, session, or application. A translation error occurs if
         this attribute appears without specifying the var or varReader attribute.
08/02/2006




                        Example 2: Simple and Fragment
                        Attributes and Variables (catalog.tag - 1)
                        <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
                        <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>

                        <%@ attribute name="bookDB" required="true" type="database.BookDB" %>
                        <%@ attribute name="color" required="true" %>

                        <%@ variable name-given="price" %>
                        <%@ variable name-given="salePrice" %>

                        <%@ attribute name="normalPrice" fragment="true" %>
                        <%@ attribute name="onSale" fragment="true" %>




                                                                                                36



         The Duke's Bookstore catalog tag, defined in catalog.tag, is a custom tag with simple
         and fragment attributes and variables. The tag renders the catalog of a book database as
         an HTML table.

         The tag file declares that it sets variables named price and salePrice via variable
         directives. The fragment normalPrice uses the variable price and the fragment onSale
         uses the variables price and salePrice. (See the resulting HTML document later in this
         presentation slides.) Before the tag invokes the fragment attributes with the jsp:invoke
         element, the Web container passes values for the variables back to the calling page.
08/02/2006




                        Example 2: Simple and Fragment
                        Attributes and Variables (catalog.tag - 2)
                        <center>
                        <table>
                        <c:forEach var="book" begin="0" items="${bookDB.books}">
                         <tr>
                         <c:set var="bookId" value="${book.bookId}" />
                         <td bgcolor="${color} ">
                            <c:url var="url" value="/bookdetails" >
                             <c:param name="bookId" value="${bookId}" />
                            </c:url>
                            <a href="${url}"><strong>${book.title}&nbsp;</strong></a></td>
                         <td bgcolor="${color} " rowspan=2>

                         <c:set var="salePrice" value="${book.price * .85}" />
                         <c:set var="price" value="${book.price}" />

                         <c:choose>
                            <c:when test="${book.onSale}" >
                             <jsp:invoke fragment="onSale" />
                            </c:when>
                            <c:otherwise>
                             <jsp:invoke fragment="normalPrice" />
                            </c:otherwise>
                          </c:choose> &nbsp;</td>                                            37



         Here if the book is on sale, we would like to perform jsp:invoke with onSale fragment.
         Otherwise, fragement normarlPrice will be used. The onSale and normalPrice
         fragments are expected to be passed from the calling JSP page. (We will see that later.)
08/02/2006




                        Example 2: Simple and Fragment
                        Attributes and Variables (catalog.tag - 3)
                         <td bgcolor="${color}" rowspan=2>
                         <c:url var="url" value="/bookcatalog" >
                          <c:param name="Add" value="${bookId}" />
                         </c:url>
                         <p><strong><a href="${url}">&nbsp;<fmt:message
                           key="CartAdd"/>&nbsp;</a></td></tr>

                         <tr>
                         <td bgcolor="#ffffff">
                         &nbsp;&nbsp;<fmt:message key="By"/> <em>${book.firstName}&nbsp;$
                           {book.surname}</em></td></tr>
                        </c:forEach>

                        </table>
                        </center>




                                                                                            38



         This contains the ending part of catalog.tag.
08/02/2006




                        Example 2: Simple and Fragment Attributes
                        and Variables (bookcatalog.jsp - 1)
                         <%@ taglib prefix="sc" tagdir="/WEB-INF/tags" %>

                         <jsp:useBean id="bookDB" class="database.BookDB" scope="page" >
                          <jsp:setProperty name="bookDB" property="database"
                             value="${bookDBAO}" />
                         </jsp:useBean>


                         <c:if test="${!empty param.Add}">
                          <c:set var="bid" value="${param.Add}"/>
                          <jsp:setProperty name="bookDB" property="bookId" value="${bid}" />
                          <c:set var="addedBook" value="${bookDB.bookDetails}" />
                            <p><h3><font color="red" size="+2">
                            <fmt:message key="CartAdded1"/> <em>${addedBook.title}</em>
                            <fmt:message key="CartAdded2"/></font></h3>
                          </c:forEach>
                         </c:if>
                                                                                               39


         This is starting part of bookcatalog.jsp which is the calling page.
08/02/2006




                        Example 2: Simple and Fragment Attributes
                        and Variables (bookcatalog.jsp - 2)
                        <c:if test="${sessionScope.cart.numberOfItems > 0}">
                         <c:url var="url" value="/bookshowcart" >
                           <c:param name="Clear" value="0" />
                           <c:param name="Remove" value="0" />
                         </c:url>
                        <p><strong><a href="${url}"><fmt:message
                           key="CartCheck"/></a>&nbsp;&nbsp;&nbsp;
                           <c:url var="url" value="/bookcashier" />
                           <a href="${url}"><fmt:message key="Buy"/></a></p></strong>
                        </c:if>

                        <br>&nbsp;
                        <br>&nbsp;
                        <h3><fmt:message key="Choose"/></h3>



                                                                                        40


         This is the middle part of calling bookcatalog.jsp page.
08/02/2006




                       Example 2: Simple and Fragment Attributes
                       and Variables (bookcatalog.jsp - 3)
                        <sc:catalog bookDB ="${bookDB}" color="#cccccc">
                         <jsp:attribute name="normalPrice">
                           <fmt:formatNumber value="${price}" type="currency"/>
                         </jsp:attribute>
                         <jsp:attribute name="onSale">
                           <strike><fmt:formatNumber value="${price}"
                           type="currency"/></strike><br/>
                           <font color="red"><fmt:formatNumber value="${salePrice}"
                           type="currency"/></font>
                         </jsp:attribute>
                        </sc:catalog>




                                                                                      41



         The page bookcatalog.jsp invokes the catalog tag with simple attributes bookDB, which
         contains catalog data, and color, which customizes the coloring of the table rows.

         The formatting of the book price is determined by two fragment attributes--normalPrice
         and onSale--that are conditionally invoked by the tag according to data retrieved from
         the book database.
08/02/2006




                        Example 2: Simple and Fragment Attributes
                        and Variables (bookcatalog.jsp - 3)




                                                                                  42


         The screen produced by bookcatalog.jsp is shown in this slide. Please note the different
         display format is used depending on whether book is a sale item or not.
08/02/2006




                                  Example 3:Repeat Tag Implemented
                                  as a Tag File
                                  <%@ taglib prefix="my"
                 Usage



                                        tagdir="/WEB-INF/tags/" %>
                                  <my:repeat num="3">
                                    tag body
                                  </my:repeat>



                                  <%-- /WEB-INF/tags/repeat.tag --%>
                 Implementation




                                  <%@ attribute name="num" %>
                                  <%@ taglib prefix="c"
                                         uri="http://java.sun.com/jsp/jstl/core" %>

                                  <c:forEach begin="1" end="${num}">
                                    <jsp:doBody />
                                  </c:forEach>

                                                                                        43


             This slide shows how repeat tag is now implemented as a tag file. As you
             can see, the implementation is not a Java class. Instead it is a another JSP
             file.
08/02/2006




              Improved
             XML Syntax

                          44
08/02/2006




                 Improved XML Syntax:
                 JSPX and TAGX
             ?   Finally, no more need for <jsp:root>!
             ?   JSP technology as an XML namespace
             ?   Ideal for outputting XML content like SVG:
                 <!-- images/hello.svg -->
                 <svg xmlns:c="http://java.sun.com/jsp/jstl/core"
                    width="8.5in" height="11.0in">
                    <c:forEach var="y" begin="3" end="10">
                       <text style="fill:blue;" y="${y*15}">
                          "Hello, ${firstName} ${lastName}!"
                       </text>
                    </c:forEach>
                 </svg>
             ?   JSP documents (.jspx) or Tag files (.tagx)
                                                                    45
08/02/2006




             Other Features


                              46
08/02/2006




             Other Features...
             ?   Central configuration via url-patterns
                 –   Map extensions other than .jsp
                 –   Enable / disable scriptlets or EL globally
                 –   Control page encoding globally
                 –   Preludes / codas
             ?   Portable debugging support through JSR-45
             ?   Dynamic attributes
             ?   Enhanced I18N support
             ?   Fragment attributes

                                                                  47
08/02/2006




             Passion!


                        48

								
To top