SlideShare ist ein Scribd-Unternehmen logo
1 von 56
Downloaden Sie, um offline zu lesen
Struts Tag Library


                         1




.
Disclaimer & Acknowledgments
?
    Even though Sang Shin is a full-time employees of Sun Microsystems, the
    contents here are created as their 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.
?
    Acknowledgments:
     – Struts' user's guide is also used in creating slides and speaker notes

     –   “Using the Struts framework” presentation material from Sue Spielman
         of Switchback Software (sspielman@switchbacksoftware.com)




                                                                                2
Revision History
?   11/10/2003: version 1: created by Sang Shin
?   Things to do
     – Speaker notes need to be added to some slides




                                                       3
Agenda
       ?   Struts tag libraries
       ?   Struts and JSTL
       ?   Struts-EL




                                                                        4




This is the agenda. We will learn first what is and why Struts. Then we
will look into Struts architecture as one that follows MVC pattern.

Struts comes with extensive tag library so we will learn how to use them.
We will also learn how internationalization is done in Struts. We will
learn how input form validation and error handling can be done. At the
end, I will talk about “Struts console” tool that you can use to graphically
edit Struts configuration file.
Struts Tag Libraries


                       5
Tag Libraries Overview
?   Number of taglibs included as part of Struts
     –   Usage is not required, but helpful
?   Bean tags
     –   Tags for accessing Beans and their properties
?   Html tags
     –   Form bridge between JSP view and other components
?   Logic tags
     –   Provides presentation logic tags that eliminate need for scriptlets
?   Template tags (Tiles in v1.1)
     –   Tags to form JSP templates that include parameterized content
?   Nested Tags (v1.1)
     –   Allows for object hierarchy
     –   Helpful for rendering lists of lists
                                                                               6
Access to Tag Libraries
    ?   All tag libraries are defined in web.xml using
        <taglib> element

        <!-- Struts Tag Library Descriptors -->
         <taglib>
           <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
           <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
         </taglib>

         <taglib>
          <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
          <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
         </taglib>                                                       7
          …



As was mentioned before, the tag libraries need to be declared in
web.xml deployment descriptor.
Bean Tags
            8
Bean Tags
       ?   Tags for accessing beans and their
           properties (not altering, however)
       ?   Enhancements to <jsp:useBean>
           –   Some of the attributes, for example id, name,
               property, and scope, share same meanings
       ?   Convenient mechanisms to create new
           beans based on the value of:
           –   User entered parameters
           –   Request headers
           –   Cookies
                                                               9




The quot;struts-beanquot; tag library contains JSP custom tags useful in
defining new beans (in any desired scope) from a variety of
possible sources, as well as a tag to render a particular bean (or
bean property) to the output response.

This tag library contains tags useful in accessing beans and their
properties, as well as defining new beans (based on these
accesses) that are accessible to the remainder of the page via
scripting variables and page scope attributes. Convenient
mechanisms to create new beans based on the value of request
cookies, headers, and parameters are also provided.
Attributes of Bean Tags
       ?   id - define a bean
       ?   name - refer to an existing bean (the value is
           either the value of an id attribute in a previous
           tag, or is found in application, session,
           request, or page scope)
       ?   property - a property from a bean
       ?   scope - scope to search for the bean. If
           scope is not specified then the bean is
           searched for in page, request, session and
           application order
                                                           10




The quot;struts-beanquot; tag library contains JSP custom tags useful in
defining new beans (in any desired scope) from a variety of
possible sources, as well as a tag to render a particular bean (or
bean property) to the output response.

This tag library contains tags useful in accessing beans and their
properties, as well as defining new beans (based on these
accesses) that are accessible to the remainder of the page via
scripting variables and page scope attributes. Convenient
mechanisms to create new beans based on the value of request
cookies, headers, and parameters are also provided.
Bean Tags
    ?   <bean:define/>
    ?   <bean:write/>
    ?   <bean:message/>
    ?   <bean:include/>
    ?   <bean:resource/>
    ?   <bean:cookie>
    ?   <bean:header>
    ?   <bean:parameter>
    ?   <bean:size>
                           11



.
<bean:define/>
    ?   For creating variables from beans and
        properties
        –   Without it, you would have to create Java code-
            based scripting variables in your JSP pages
    ?   The variables are used later in the JSP
        page
    ?   For exposing Java objects (i.e. Collections)
        that are created in a Action class to a JSP


                                                              12



.
Examples: <bean:define/>
    ?   <bean:define id=quot;stringquot; value=quot;Struts in
        Javaboutiquequot;/>
        –   Get a bean with a String constant
    ?   <bean:define id=quot;copyquot; name=quot;dvdquot;/>
        –   Get an existing bean
    ?   <bean:define id=quot;titlequot; name=quot;copyquot;
        property=quot;titlequot;/>
        –   Get a single property from a bean



                                                    13



.
Example1: favorites.jsp (ch 03)
     1   <c:forEach var=quot;theColorquot; items=quot;${FavoritesForm.colors}quot;
     varStatus=quot;loopStatusquot;>
     2     <bean:define id=quot;ctrquot;>
     3      <c:out value=quot;${loopStatus.index}quot;/>
     4     </bean:define>
     5 <br/><html:text property='<%=quot;color[quot;+ctr+quot;]quot;%>'/>
     6    </c:forEach>




                                                                     14




Here in this example, the lastname property of bean is rendered to
output reponse being created by the JSP page.
Example2: view_favorites.jsp (ch 03)
     1  <bean:define id=quot;favsquot; name=quot;FavoritesFormquot;/>
     2 <script language=quot;JavaScriptquot;>
     3   function showMessage() {
     4     alert( quot;Hello, <bean:write name='favs' property='name'/>!quot; );
     5   }
     6 </script>
     7   <p>
     8     Thanks for responding, <bean:write name=quot;favsquot; property=quot;namequot;/> !<br/>
     9     <a href=quot;javascript:showMessage()quot;>Click Me</a>
     10 </p>
     11 <p>You have indicated that your favorite colors are:
     12    <ul>
     13      <li><bean:write name=quot;favsquot; property=quot;color[0]quot;/></li>
     14      <li><bean:write name=quot;favsquot; property=quot;color[1]quot;/></li>
     15      <li><bean:write name=quot;favsquot; property=quot;color[2]quot;/></li>
     16    </ul>
     17    <ul>
     18      <c:forEach var=quot;colorquot; items=quot;${favs.color}quot;>
     19       <li><c:out value=quot;${color}quot;/></li>                               15
     20      </c:forEach>



Here in this example, the lastname property of bean is rendered to
output reponse being created by the JSP page.
Example2: FovoritesForm Class (ch 03)
     1   public final class FavoritesForm extends ActionForm {
     2
     3 private static String[] javaIdes = new String[] {quot;Eclipsequot;, quot;IDEAquot;, quot;JBuilderquot;,
     quot;JDeveloperquot;, quot;NetBeansquot;};
     4 private static String[] csharpIdes = new String[] {quot;SharpDevelopquot;, quot;Visual
     Studioquot;};
     5
     6 public FavoritesForm() {
     7       webLinks = new ArrayList();
     8       for (int i=0; i<5; i++) webLinks.add(new WebLink());
     9       colors = new String[3];
     10            colors[0]=quot;Blackquot;;
     11            colors[1]=quot;Bluequot;;
     12            colors[2]=quot;Redquot;;
     13      }
     14      ...
     15     public String[] getColors() {
     16         return colors;
     17     }                                                                          16
     18     public void setColors(String[] colors) {



Here in this example, the lastname property of bean is rendered to
output reponse being created by the JSP page.
<bean:write/>
    ?   Use it to output the contents of a bean's
        property
    ?   The information returned to the page is
        rendered as a String
    ?   Use it to encode and unencode information




                                                17



.
Example1: <bean:write/>
    <jsp:useBean id=quot;dvdquot; class=quot;hansen.playground.DVDquot;
     scope=quot;requestquot;/>
    ...
    <jsp:getProperty name=quot;dvdquot; property=quot;titlequot;/>


    Using Struts you simply use the write tag:


    <bean:write name=quot;dvdquot; property=quot;titlequot; scope=quot;requestquot;/>




                                                                18



.
Example2: submitAction.java
        1 public final class SubmitAction extends Action {
        2
        3  // The execute() method is where you provide your business logic
        4  public ActionForward execute(ActionMapping mapping,
        5                     ActionForm form,
        6                     HttpServletRequest request,
        7                     HttpServletResponse response) {
        8
        9    // Cast ActionForm object to SubmitForm type
        10     SubmitForm f = (SubmitForm) form;
        11
        12     // Retrieve the value of lastname field
        13     String lastName = f.getLastName();
        14
        15     // Translate the lastname to upper case and save it Request scope
        16     request.setAttribute(quot;lastNamequot;, lastName.toUpperCase());
        17
        18     // Create and return ActionForward object with quot;successquot; outcome
        19     return (mapping.findForward(quot;successquot;));
        20   }
        21 }                                                                       19
        22




Here in this example, the lastname property of bean is rendered to
output reponse being created by the JSP page.
Example2: submit.jsp
        1    <logic:present name=quot;lastNamequot; scope=quot;requestquot;>
        2    Hello
        3    <logic:equal name=quot;submitFormquot; property=quot;agequot; value=quot;aquot;>
        4     young
        5    </logic:equal>
        6    <logic:equal name=quot;submitFormquot; property=quot;agequot; value=quot;cquot;>
        7     old
        8    </logic:equal>
        9    <bean:write name=quot;lastNamequot; scope=quot;requestquot;/>
        10    </logic:present>
        11
        12    </body>
        13    </html>




                                                                        20




Here in this example, the lastname property of bean is rendered to
output reponse being created by the JSP page.
Example3: view_favorites.jsp (ch 03)
     1  <bean:define id=quot;favsquot; name=quot;FavoritesFormquot;/>
     2 <script language=quot;JavaScriptquot;>
     3   function showMessage() {
     4     alert( quot;Hello, <bean:write name='favs' property='name'/>!quot; );
     5   }
     6 </script>
     7   <p>
     8     Thanks for responding, <bean:write name=quot;favsquot; property=quot;namequot;/> !<br/>
     9     <a href=quot;javascript:showMessage()quot;>Click Me</a>
     10 </p>
     11 <p>You have indicated that your favorite colors are:
     12    <ul>
     13      <li><bean:write name=quot;favsquot; property=quot;color[0]quot;/></li>
     14      <li><bean:write name=quot;favsquot; property=quot;color[1]quot;/></li>
     15      <li><bean:write name=quot;favsquot; property=quot;color[2]quot;/></li>
     16    </ul>
     17    <ul>
     18      <c:forEach var=quot;colorquot; items=quot;${favs.color}quot;>
     19       <li><c:out value=quot;${color}quot;/></li>                               21
     20      </c:forEach>



Here in this example, the lastname property of bean is rendered to
output reponse being created by the JSP page.
<bean:message/>
    ?   Looks up a key in the resource file




                                              22



.
Example: index.jsp (ch 03)
     1    <html:html locale=quot;truequot;>
     2    <head>
     3    <title><bean:message key=quot;index.titlequot;/></title>
     4    <html:base/>
     5    </head>
     6    <body bgcolor=quot;whitequot;>
     7    <h2>Struts Chapter 3 Examples</h2>
     8
     9    <p>
     10      <bean:message key=quot;msg.helloquot;/>
     11    </p>




                                                              23




Here in this example, the lastname property of bean is rendered to
output reponse being created by the JSP page.
<bean:parameter/>
    ?   Get a request parameter
    ?   Example
        –   <bean:parameter id=quot;reqquot; name=quot;itemquot; />




                                                      24



.
HTML Tags
            25
HTML Tags
       ?   Form bridge between JSP view and other
           components
       ?   Input forms are important for gathering user-
           entered data
       ?   Most of the actions of the HTML taglib involve
           HTML forms
       ?   Error messages, hyperlinking,
           internationalization


                                                            26




The tags in the Struts HTML library form a bridge between a
JSP view and the other components of a Web application. Since
a dynamic Web application often depends on gathering data
from a user, input forms play an important role in the Struts
framework. Consequently, the majority of the HTML tags
involve HTML forms.

The HTML taglib contains tags used to create Struts input
forms, as well as other tags generally useful in the creation of
HTML-based user interfaces. The output is HTML 4.01
compliant or XHTML 1.0 when in XHTML mode.
HTML Tag Resources
HTML Tags
        ?   checkboxes
        ?   hidden fields
        ?   password input fields
        ?   radio buttons
        ?   reset buttons
        ?   select lists with embedded option or options items
        ?   option
        ?   options
        ?   submit buttons
        ?   text input fields
        ?   textareas
                                                                 27




This is the list of HTML tags that allowssome types of inputs
from a user.

In every case, a field tag must be nested within a form tag, so
that the field knows what bean to use for initializing displayed
values.
HTML Tags
    ?   <html:errors/>
    ?   <html:messages/>
    ?   <html:html>
    ?   <html:form>
    ?   <html:link>
    ?   <html:text>



                           28



.
<html:errors/>
    ?   Simplest way to display error messages
        –   It is expected that ActionErrors is created (either in
            the validate() method of an ActionForm class or in
            execute() method of an Action class)
    ?   Place the tag anywhere on the page you
        want the list of errors to be displayed
    ?   Iterates over the errors writing unescaped
        contents to the page
        –   Messages need to have HTML tags, which are not
            desirable
                                                                29



.
Example: submit.jsp
1    <%@ page language=quot;javaquot; %>
2    <%@ taglib uri=quot;/WEB-INF/struts-bean.tldquot; prefix=quot;beanquot; %>
3    <%@ taglib uri=quot;/WEB-INF/struts-html.tldquot; prefix=quot;htmlquot; %>
4    <%@ taglib uri=quot;/WEB-INF/struts-logic.tldquot; prefix=quot;logicquot; %>
5
6    <html>
7    <head><title>Submit example</title></head>
8    <body>
9
10    <h3>Example Submit Page</h3>
11
12    <html:errors/>
13
14    <html:form action=quot;submit.doquot;>
15    Last Name: <html:text property=quot;lastNamequot;/><br>
16    Address: <html:textarea property=quot;addressquot;/><br>
17    Sex:    <html:radio property=quot;sexquot; value=quot;Mquot;/>Male
18          <html:radio property=quot;sexquot; value=quot;Fquot;/>Female<br>
19    Married: <html:checkbox property=quot;marriedquot;/><br>
20    Age:    <html:select property=quot;agequot;>
21           <html:option value=quot;aquot;>0-19</html:option>
22           <html:option value=quot;bquot;>20-49</html:option>
23           <html:option value=quot;cquot;>50-</html:option>               30
24          </html:select><br>
Example: ApplicationResources.properties
1 errors.header= <h4> Validation Error(s)</h4><ul>
2
3 error.lastName=<li>Enter your last name
4 error.address= <li>Enter your address
5 error.sex= <li>Enter your sex
6 error.age=<li>Enter your age
7 error.birthYear=<li>Enter the year you were born between 1900 and 2004
inclusive
8
9 errors.footer= </ul><hr>




                                                                           31
<html:messages/>
    ?   Corrects the problem of <html:errors/>
        –   Allows you to keep HTML tags in JSP pages not in
            the resource file
    ?   By default, it looks for error messages
        stored in the request scope
    ?   The id attribute defines the name of the
        scripting variable used to expose the error
        message text


                                                          32



.
Logic Tags
             33
Logic Tags
       ?   Provides presentation logic tags that
           eliminate need for scriptlets
       ?   Value comparisons
           Include: = != <= >= < >
       ?   Substring matching
           –   match, notmatch
       ?   Presentation logic
           –   forward, redirect
       ?   Collections
           –   iterate                                      34




The quot;struts-logicquot; tag library contains tags that are useful in
managing conditional generation of output text, looping over
object collections for repetitive generation of output text, and
application flow management
Logic Tags
    ?   <logic:present/>
    ?   <logic:equal/>




                           35



.
<logic:present/> &
    <logic:notPresent> tags
    ?   The body of the <logic:present/> tag is
        evaluated whenever the JavaBean, or its
        property, is present within the JSP page
    ?   Attributes for evaluation
        –   name
        –   parameter
        –   cookie
        –   header
        –   property

                                                   36



.
Example: submit.jsp
    1 <logic:present name=quot;lastNamequot; scope=quot;requestquot;>
    2       Hello
    3       <logic:equal name=quot;submitFormquot; property=quot;agequot; value=quot;aquot;>
    4         young
    5       </logic:equal>
    6       <logic:equal name=quot;submitFormquot; property=quot;agequot; value=quot;cquot;>
    7        old
    8       </logic:equal>
    9      <bean:write name=quot;lastNamequot; scope=quot;requestquot;/>
    10 </logic:present>
    11
    12 </body>
    13 </html>




<                                                                      37
<logic:equal/> & <logic:notEqual>
    tags
    ?   Checks against a specific value in a bean
    ?   Assumes the bean exists
        –   Exception occurs if not
    ?   <logic:equal/> tag compares the bean's
        toString() value aganst the value property
    ?   If property attribute is specified, then the
        value attribute is compared against the
        bean's property

                                                       38



.
Example: submit.jsp
    1 <logic:present name=quot;lastNamequot; scope=quot;requestquot;>
    2       Hello
    3       <logic:equal name=quot;submitFormquot; property=quot;agequot; value=quot;aquot;>
    4         young
    5       </logic:equal>
    6       <logic:equal name=quot;submitFormquot; property=quot;agequot; value=quot;cquot;>
    7        old
    8       </logic:equal>
    9      <bean:write name=quot;lastNamequot; scope=quot;requestquot;/>
    10 </logic:present>
    11
    12 </body>
    13 </html>




<                                                                      39
Usage Example: <logic:equal/> &
    <logic:notEqual> tags
    ?   You want to present different messages or
        buttons on a page depending upon the type
        of action you migt perform
    ?   Example:
        –   Depending what a user wants to do (mode) –
            view, edit, or delete, you want to present different
            set of buttons
        –   View mode: Show only view button
        –   Edit mode: Show view and edit buttons
        –   Delete mode: Show only delete button
                                                               40



.
Example: subscription.jsp (ch 13)
    1    <html:html>
    2    <head>
    3    <logic:equal name=quot;SubscriptionFormquot; property=quot;actionquot;
    4             scope=quot;requestquot; value=quot;Createquot;>
    5     <title><bean:message key=quot;subscription.title.createquot;/></title>
    6    </logic:equal>
    7    <logic:equal name=quot;SubscriptionFormquot; property=quot;actionquot;
    8             scope=quot;requestquot; value=quot;Deletequot;>
    9     <title><bean:message key=quot;subscription.title.deletequot;/></title>
    10    </logic:equal>
    11    <logic:equal name=quot;SubscriptionFormquot; property=quot;actionquot;
    12             scope=quot;requestquot; value=quot;Editquot;>
    13      <title><bean:message key=quot;subscription.title.editquot;/></title>
    14    </logic:equal>
    15    <html:base/>


<                                                                          41
Template Tags
                42
Template Tags
?   Templates are JSP pages that include
    parameterized content
?   Useful for creating dynamic JSP templates
    for pages that share a common format
?   Functionality provided is similar to what
    can be achieved using the standard JSP
    include directive, but these tags allow for
    dynamic rather than static content


                                                  43
Template Tags
?   Three template tags work in an
    interrelated function:
    –   Get - Gets the content from request scope
        that was put there by a put tag.
    –   Insert - Includes a template
    –   Put - Puts content into request scope




                                                    44
Template sample (insert/put)
<template:insert template='/layout.jsp'>
    <template:put name='title'
             content='CD Manager Logon‘/>
    <template:put name='header' content='/header.jsp' />
    <template:put name='content‘
                  content='/logonContent.jsp'/>
    <template:put name='footer' content='/footer.jsp' />
</template:insert>



                                                           45
layout.jsp
<html>
  <head>
     <title> <template:get name='title'/> </title>
  </head>
   <body >
    <table>
      <tr><td> <template:get name='header'/> </td></tr>
     <tr><td> <template:get name='content'/> </td></tr>
      <tr><td> <template:get name='footer'/> </td></tr>
     </table>
   </body>
</html>


                                                          46
Struts and
   JSTL

             47
When to JSTL in your Struts
         application?
     ?   Developers should evaluate when to use
         the JSTL
     ?   Many of the Struts taglib features are now
         available in the JSTL
     ?   It’s simple: If the tag exists in the JSTL –
         use it
     ?   Continue using the Struts tags where
         appropriate, they will continue to be
         supported
                                                           48




Some of the features in this taglib are also available in the
JavaServer Pages Standard Tag Library (JSTL). The Struts team
encourages the use of the standard tags over the Struts specific
tags when possible.
Interaction with JSTL
?   Struts-el taglibs allow for using expression
    values instead of just rtexprvalue
      Runtime: <bean:message key='<%= stringvar %>'/>
      Expression: <bean-el:message key=quot;${stringvar}quot;/>
?   Set of optional taglibs that can be used with
    the JSTL expression language (EL)
?   Implements many (but not all) of the Struts
    tags.
?   Located in the contrib folder of the Struts
    release
?   Container with servlet 2.3 support required           49
Struts EL
Tag library

              50
Struts EL Extension
             ?   Extension of the Struts tag library
             ?   Uses the expression evaluation engine in the
                 Jakarta Taglibs implementation of the JSP
                 Standard Tag Library (version 1.0) to evaluate
                 attribute values
             ?   Some of the Struts tags were not ported to this
                 library
                 –   their functionality was entirely supplied by the
                     JSTL

This subprojectRequires theof the Struts tag library. Each JSP custom tag in this
                   is an extension use of the Struts tag library, and
             ?


library is a subclass of an associated Pages Standardlibrary.Library
                  the Java Server tag in the Struts tag Tag One difference is
                                                                             51
that this tag library does not use quot;rtexprvaluesquot;, it uses the expression evaluation
engine in the Jakarta Taglibs implementation of the JSP Standard Tag Library
(version 1.0) to evaluate attribute values.

In addition, some of the Struts tags were not ported to this library, as it was
determined that their functionality was entirely supplied by the JSTL. These
particular Struts tags, and the reason for their non-porting will be described in the
documentation for this library.

In order to fully understand the correct utilization of this library, you must
understand the use and operation of the Struts tag library, and the use and operation
of the JavaServer Pages Standard Tag Library (hereafter called the quot;JSTLquot;), along
with the expression language (sometimes called the quot;ELquot;) used for evaluating
attribute values.

The Struts-EL tag library requires the use of the Struts tag library, and the Java
Server Pages Standard Tag Library. It is not necessary for JSP pages using the Struts-
EL tag library to also use the Struts tags or the JSTL tags, but the Struts and JSTL tag
libraries need to be part of the application utilizing the Struts-EL tag library.

This is because the Struts-EL tag classes are all subclasses of Struts tag classes, and
their implementation uses classes provided by the JSTL.
Tag Mapping
             ?   Every Struts tag that provides a feature that
                 is not covered by the JSTL (1.0) library is
                 mapped into the Struts-EL library
             ?   Bean Tag Library Tags NOT Implemented
                 in Struts-EL
                 –   cookie (in Struts): c:set, EL (in JSTL)
                 –   define (in Struts), c:set, EL (In JSTL)




                                                                           52




 In implementing the Struts-EL library, every Struts tag that provides a feature that
is not covered by the JSTL (1.0) library is mapped into the Struts-EL library. This
section reviews which Struts tags are NOT implemented in the Struts-EL library,
and which JSTL tags provide that feature.

Many of the non-porting decisions were based on the fact that the JSTL
expression language itself provides the same functionality. In those cases, in
addition to a possible JSTL tag name, the symbol quot;ELquot; will be listed.
How to use Struts EL
             ?   Struts
                 –   <bean:message key='<%= stringvar %>'/>
             ?   Struts EL
                 –   <bean-el:message key=quot;${stringvar}quot;/>




                                                                             53



 The Struts-EL tag library is a contributed library in the Struts distribution. It
represents an integration of the Struts tag library with the JavaServer Pages
Standard Tag Library, or at least the quot;expression evaluationquot; engine that is used
by the JSTL.

The base Struts tag library contains tags which rely on the evaluation of
quot;rtexprvaluequot;s (runtime scriptlet expressions) to evaluate dynamic attribute
values. For instance, to print a message from a properties file based on a resource
key, you would use the bean:write tag, perhaps like this:


  <bean:message key='<%= stringvar %>'/>


This assumes that stringvar exists as a JSP scripting variable. If you're using the
Struts-EL library, the reference looks very similar, but slightly different, like this:


  <bean-el:message key=quot;${stringvar}quot;/>
Best Practice
 Guidelines

                54
Follow Good MVC Practice
    ?   JSP pages must “know” as little as possible
        about the back-end architecture
    ?   JSP page should only concern itself with
        rendering the view and not manipulating
        any data logic




                                                  55



.
Passion!


           56

Weitere ähnliche Inhalte

Andere mochten auch

What do the national foresight activities tell us? The experience of Estonian...
What do the national foresight activities tell us? The experience of Estonian...What do the national foresight activities tell us? The experience of Estonian...
What do the national foresight activities tell us? The experience of Estonian...
Marek Tiits
 
Step By Step Guide For Buidling Simple Struts App Speakernoted
Step By Step Guide For Buidling Simple Struts App SpeakernotedStep By Step Guide For Buidling Simple Struts App Speakernoted
Step By Step Guide For Buidling Simple Struts App Speakernoted
Harjinder Singh
 
Social Studies - All About Me
Social Studies - All About MeSocial Studies - All About Me
Social Studies - All About Me
Catherine Connor
 
Como escribir un plan de mercado
Como escribir  un plan de mercadoComo escribir  un plan de mercado
Como escribir un plan de mercado
campir
 

Andere mochten auch (10)

La apatía
La apatíaLa apatía
La apatía
 
Exploratory2
Exploratory2Exploratory2
Exploratory2
 
Barack Obama
Barack ObamaBarack Obama
Barack Obama
 
Exploratory2
Exploratory2Exploratory2
Exploratory2
 
What do the national foresight activities tell us? The experience of Estonian...
What do the national foresight activities tell us? The experience of Estonian...What do the national foresight activities tell us? The experience of Estonian...
What do the national foresight activities tell us? The experience of Estonian...
 
Step By Step Guide For Buidling Simple Struts App Speakernoted
Step By Step Guide For Buidling Simple Struts App SpeakernotedStep By Step Guide For Buidling Simple Struts App Speakernoted
Step By Step Guide For Buidling Simple Struts App Speakernoted
 
Social Studies - All About Me
Social Studies - All About MeSocial Studies - All About Me
Social Studies - All About Me
 
Process Skill 1
Process Skill 1Process Skill 1
Process Skill 1
 
Como escribir un plan de mercado
Como escribir  un plan de mercadoComo escribir  un plan de mercado
Como escribir un plan de mercado
 
Struts Basics
Struts BasicsStruts Basics
Struts Basics
 

Ähnlich wie Struts Tags Speakernoted

Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
Baruch Sadogursky
 
Struts Intro Course(1)
Struts Intro Course(1)Struts Intro Course(1)
Struts Intro Course(1)
wangjiaz
 
NHibernate (The ORM For .NET Platform)
NHibernate (The ORM For .NET Platform)NHibernate (The ORM For .NET Platform)
NHibernate (The ORM For .NET Platform)
Samnang Chhun
 
Nhibernatethe Orm For Net Platform 1226744632929962 8
Nhibernatethe Orm For Net Platform 1226744632929962 8Nhibernatethe Orm For Net Platform 1226744632929962 8
Nhibernatethe Orm For Net Platform 1226744632929962 8
Nicolas Thon
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
Ankur Dongre
 

Ähnlich wie Struts Tags Speakernoted (20)

Ibm
IbmIbm
Ibm
 
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
 
Spring and DWR
Spring and DWRSpring and DWR
Spring and DWR
 
Jsp
JspJsp
Jsp
 
Struts Intro Course(1)
Struts Intro Course(1)Struts Intro Course(1)
Struts Intro Course(1)
 
Compass Framework
Compass FrameworkCompass Framework
Compass Framework
 
Spring Surf 101
Spring Surf 101Spring Surf 101
Spring Surf 101
 
I Feel Pretty
I Feel PrettyI Feel Pretty
I Feel Pretty
 
Boston Computing Review - Java Server Pages
Boston Computing Review - Java Server PagesBoston Computing Review - Java Server Pages
Boston Computing Review - Java Server Pages
 
Struts2
Struts2Struts2
Struts2
 
NHibernate (The ORM For .NET Platform)
NHibernate (The ORM For .NET Platform)NHibernate (The ORM For .NET Platform)
NHibernate (The ORM For .NET Platform)
 
สปริงเฟรมเวิร์ค4.1
สปริงเฟรมเวิร์ค4.1สปริงเฟรมเวิร์ค4.1
สปริงเฟรมเวิร์ค4.1
 
Extending MySQL Enterprise Monitor
Extending MySQL Enterprise MonitorExtending MySQL Enterprise Monitor
Extending MySQL Enterprise Monitor
 
Learning jsp
Learning jspLearning jsp
Learning jsp
 
JSUG - Spring by Christoph Pickl
JSUG - Spring by Christoph PicklJSUG - Spring by Christoph Pickl
JSUG - Spring by Christoph Pickl
 
Nhibernatethe Orm For Net Platform 1226744632929962 8
Nhibernatethe Orm For Net Platform 1226744632929962 8Nhibernatethe Orm For Net Platform 1226744632929962 8
Nhibernatethe Orm For Net Platform 1226744632929962 8
 
Javascript
JavascriptJavascript
Javascript
 
Intro to Rails ActiveRecord
Intro to Rails ActiveRecordIntro to Rails ActiveRecord
Intro to Rails ActiveRecord
 
Unified Expression Language
Unified Expression LanguageUnified Expression Language
Unified Expression Language
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
 

Kürzlich hochgeladen

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Kürzlich hochgeladen (20)

Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 

Struts Tags Speakernoted

  • 2. Disclaimer & Acknowledgments ? Even though Sang Shin is a full-time employees of Sun Microsystems, the contents here are created as their 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. ? Acknowledgments: – Struts' user's guide is also used in creating slides and speaker notes – “Using the Struts framework” presentation material from Sue Spielman of Switchback Software (sspielman@switchbacksoftware.com) 2
  • 3. Revision History ? 11/10/2003: version 1: created by Sang Shin ? Things to do – Speaker notes need to be added to some slides 3
  • 4. Agenda ? Struts tag libraries ? Struts and JSTL ? Struts-EL 4 This is the agenda. We will learn first what is and why Struts. Then we will look into Struts architecture as one that follows MVC pattern. Struts comes with extensive tag library so we will learn how to use them. We will also learn how internationalization is done in Struts. We will learn how input form validation and error handling can be done. At the end, I will talk about “Struts console” tool that you can use to graphically edit Struts configuration file.
  • 6. Tag Libraries Overview ? Number of taglibs included as part of Struts – Usage is not required, but helpful ? Bean tags – Tags for accessing Beans and their properties ? Html tags – Form bridge between JSP view and other components ? Logic tags – Provides presentation logic tags that eliminate need for scriptlets ? Template tags (Tiles in v1.1) – Tags to form JSP templates that include parameterized content ? Nested Tags (v1.1) – Allows for object hierarchy – Helpful for rendering lists of lists 6
  • 7. Access to Tag Libraries ? All tag libraries are defined in web.xml using <taglib> element <!-- Struts Tag Library Descriptors --> <taglib> <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri> <taglib-location>/WEB-INF/struts-bean.tld</taglib-location> </taglib> <taglib> <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri> <taglib-location>/WEB-INF/struts-html.tld</taglib-location> </taglib> 7 … As was mentioned before, the tag libraries need to be declared in web.xml deployment descriptor.
  • 9. Bean Tags ? Tags for accessing beans and their properties (not altering, however) ? Enhancements to <jsp:useBean> – Some of the attributes, for example id, name, property, and scope, share same meanings ? Convenient mechanisms to create new beans based on the value of: – User entered parameters – Request headers – Cookies 9 The quot;struts-beanquot; tag library contains JSP custom tags useful in defining new beans (in any desired scope) from a variety of possible sources, as well as a tag to render a particular bean (or bean property) to the output response. This tag library contains tags useful in accessing beans and their properties, as well as defining new beans (based on these accesses) that are accessible to the remainder of the page via scripting variables and page scope attributes. Convenient mechanisms to create new beans based on the value of request cookies, headers, and parameters are also provided.
  • 10. Attributes of Bean Tags ? id - define a bean ? name - refer to an existing bean (the value is either the value of an id attribute in a previous tag, or is found in application, session, request, or page scope) ? property - a property from a bean ? scope - scope to search for the bean. If scope is not specified then the bean is searched for in page, request, session and application order 10 The quot;struts-beanquot; tag library contains JSP custom tags useful in defining new beans (in any desired scope) from a variety of possible sources, as well as a tag to render a particular bean (or bean property) to the output response. This tag library contains tags useful in accessing beans and their properties, as well as defining new beans (based on these accesses) that are accessible to the remainder of the page via scripting variables and page scope attributes. Convenient mechanisms to create new beans based on the value of request cookies, headers, and parameters are also provided.
  • 11. Bean Tags ? <bean:define/> ? <bean:write/> ? <bean:message/> ? <bean:include/> ? <bean:resource/> ? <bean:cookie> ? <bean:header> ? <bean:parameter> ? <bean:size> 11 .
  • 12. <bean:define/> ? For creating variables from beans and properties – Without it, you would have to create Java code- based scripting variables in your JSP pages ? The variables are used later in the JSP page ? For exposing Java objects (i.e. Collections) that are created in a Action class to a JSP 12 .
  • 13. Examples: <bean:define/> ? <bean:define id=quot;stringquot; value=quot;Struts in Javaboutiquequot;/> – Get a bean with a String constant ? <bean:define id=quot;copyquot; name=quot;dvdquot;/> – Get an existing bean ? <bean:define id=quot;titlequot; name=quot;copyquot; property=quot;titlequot;/> – Get a single property from a bean 13 .
  • 14. Example1: favorites.jsp (ch 03) 1 <c:forEach var=quot;theColorquot; items=quot;${FavoritesForm.colors}quot; varStatus=quot;loopStatusquot;> 2 <bean:define id=quot;ctrquot;> 3 <c:out value=quot;${loopStatus.index}quot;/> 4 </bean:define> 5 <br/><html:text property='<%=quot;color[quot;+ctr+quot;]quot;%>'/> 6 </c:forEach> 14 Here in this example, the lastname property of bean is rendered to output reponse being created by the JSP page.
  • 15. Example2: view_favorites.jsp (ch 03) 1 <bean:define id=quot;favsquot; name=quot;FavoritesFormquot;/> 2 <script language=quot;JavaScriptquot;> 3 function showMessage() { 4 alert( quot;Hello, <bean:write name='favs' property='name'/>!quot; ); 5 } 6 </script> 7 <p> 8 Thanks for responding, <bean:write name=quot;favsquot; property=quot;namequot;/> !<br/> 9 <a href=quot;javascript:showMessage()quot;>Click Me</a> 10 </p> 11 <p>You have indicated that your favorite colors are: 12 <ul> 13 <li><bean:write name=quot;favsquot; property=quot;color[0]quot;/></li> 14 <li><bean:write name=quot;favsquot; property=quot;color[1]quot;/></li> 15 <li><bean:write name=quot;favsquot; property=quot;color[2]quot;/></li> 16 </ul> 17 <ul> 18 <c:forEach var=quot;colorquot; items=quot;${favs.color}quot;> 19 <li><c:out value=quot;${color}quot;/></li> 15 20 </c:forEach> Here in this example, the lastname property of bean is rendered to output reponse being created by the JSP page.
  • 16. Example2: FovoritesForm Class (ch 03) 1 public final class FavoritesForm extends ActionForm { 2 3 private static String[] javaIdes = new String[] {quot;Eclipsequot;, quot;IDEAquot;, quot;JBuilderquot;, quot;JDeveloperquot;, quot;NetBeansquot;}; 4 private static String[] csharpIdes = new String[] {quot;SharpDevelopquot;, quot;Visual Studioquot;}; 5 6 public FavoritesForm() { 7 webLinks = new ArrayList(); 8 for (int i=0; i<5; i++) webLinks.add(new WebLink()); 9 colors = new String[3]; 10 colors[0]=quot;Blackquot;; 11 colors[1]=quot;Bluequot;; 12 colors[2]=quot;Redquot;; 13 } 14 ... 15 public String[] getColors() { 16 return colors; 17 } 16 18 public void setColors(String[] colors) { Here in this example, the lastname property of bean is rendered to output reponse being created by the JSP page.
  • 17. <bean:write/> ? Use it to output the contents of a bean's property ? The information returned to the page is rendered as a String ? Use it to encode and unencode information 17 .
  • 18. Example1: <bean:write/> <jsp:useBean id=quot;dvdquot; class=quot;hansen.playground.DVDquot; scope=quot;requestquot;/> ... <jsp:getProperty name=quot;dvdquot; property=quot;titlequot;/> Using Struts you simply use the write tag: <bean:write name=quot;dvdquot; property=quot;titlequot; scope=quot;requestquot;/> 18 .
  • 19. Example2: submitAction.java 1 public final class SubmitAction extends Action { 2 3 // The execute() method is where you provide your business logic 4 public ActionForward execute(ActionMapping mapping, 5 ActionForm form, 6 HttpServletRequest request, 7 HttpServletResponse response) { 8 9 // Cast ActionForm object to SubmitForm type 10 SubmitForm f = (SubmitForm) form; 11 12 // Retrieve the value of lastname field 13 String lastName = f.getLastName(); 14 15 // Translate the lastname to upper case and save it Request scope 16 request.setAttribute(quot;lastNamequot;, lastName.toUpperCase()); 17 18 // Create and return ActionForward object with quot;successquot; outcome 19 return (mapping.findForward(quot;successquot;)); 20 } 21 } 19 22 Here in this example, the lastname property of bean is rendered to output reponse being created by the JSP page.
  • 20. Example2: submit.jsp 1 <logic:present name=quot;lastNamequot; scope=quot;requestquot;> 2 Hello 3 <logic:equal name=quot;submitFormquot; property=quot;agequot; value=quot;aquot;> 4 young 5 </logic:equal> 6 <logic:equal name=quot;submitFormquot; property=quot;agequot; value=quot;cquot;> 7 old 8 </logic:equal> 9 <bean:write name=quot;lastNamequot; scope=quot;requestquot;/> 10 </logic:present> 11 12 </body> 13 </html> 20 Here in this example, the lastname property of bean is rendered to output reponse being created by the JSP page.
  • 21. Example3: view_favorites.jsp (ch 03) 1 <bean:define id=quot;favsquot; name=quot;FavoritesFormquot;/> 2 <script language=quot;JavaScriptquot;> 3 function showMessage() { 4 alert( quot;Hello, <bean:write name='favs' property='name'/>!quot; ); 5 } 6 </script> 7 <p> 8 Thanks for responding, <bean:write name=quot;favsquot; property=quot;namequot;/> !<br/> 9 <a href=quot;javascript:showMessage()quot;>Click Me</a> 10 </p> 11 <p>You have indicated that your favorite colors are: 12 <ul> 13 <li><bean:write name=quot;favsquot; property=quot;color[0]quot;/></li> 14 <li><bean:write name=quot;favsquot; property=quot;color[1]quot;/></li> 15 <li><bean:write name=quot;favsquot; property=quot;color[2]quot;/></li> 16 </ul> 17 <ul> 18 <c:forEach var=quot;colorquot; items=quot;${favs.color}quot;> 19 <li><c:out value=quot;${color}quot;/></li> 21 20 </c:forEach> Here in this example, the lastname property of bean is rendered to output reponse being created by the JSP page.
  • 22. <bean:message/> ? Looks up a key in the resource file 22 .
  • 23. Example: index.jsp (ch 03) 1 <html:html locale=quot;truequot;> 2 <head> 3 <title><bean:message key=quot;index.titlequot;/></title> 4 <html:base/> 5 </head> 6 <body bgcolor=quot;whitequot;> 7 <h2>Struts Chapter 3 Examples</h2> 8 9 <p> 10 <bean:message key=quot;msg.helloquot;/> 11 </p> 23 Here in this example, the lastname property of bean is rendered to output reponse being created by the JSP page.
  • 24. <bean:parameter/> ? Get a request parameter ? Example – <bean:parameter id=quot;reqquot; name=quot;itemquot; /> 24 .
  • 25. HTML Tags 25
  • 26. HTML Tags ? Form bridge between JSP view and other components ? Input forms are important for gathering user- entered data ? Most of the actions of the HTML taglib involve HTML forms ? Error messages, hyperlinking, internationalization 26 The tags in the Struts HTML library form a bridge between a JSP view and the other components of a Web application. Since a dynamic Web application often depends on gathering data from a user, input forms play an important role in the Struts framework. Consequently, the majority of the HTML tags involve HTML forms. The HTML taglib contains tags used to create Struts input forms, as well as other tags generally useful in the creation of HTML-based user interfaces. The output is HTML 4.01 compliant or XHTML 1.0 when in XHTML mode. HTML Tag Resources
  • 27. HTML Tags ? checkboxes ? hidden fields ? password input fields ? radio buttons ? reset buttons ? select lists with embedded option or options items ? option ? options ? submit buttons ? text input fields ? textareas 27 This is the list of HTML tags that allowssome types of inputs from a user. In every case, a field tag must be nested within a form tag, so that the field knows what bean to use for initializing displayed values.
  • 28. HTML Tags ? <html:errors/> ? <html:messages/> ? <html:html> ? <html:form> ? <html:link> ? <html:text> 28 .
  • 29. <html:errors/> ? Simplest way to display error messages – It is expected that ActionErrors is created (either in the validate() method of an ActionForm class or in execute() method of an Action class) ? Place the tag anywhere on the page you want the list of errors to be displayed ? Iterates over the errors writing unescaped contents to the page – Messages need to have HTML tags, which are not desirable 29 .
  • 30. Example: submit.jsp 1 <%@ page language=quot;javaquot; %> 2 <%@ taglib uri=quot;/WEB-INF/struts-bean.tldquot; prefix=quot;beanquot; %> 3 <%@ taglib uri=quot;/WEB-INF/struts-html.tldquot; prefix=quot;htmlquot; %> 4 <%@ taglib uri=quot;/WEB-INF/struts-logic.tldquot; prefix=quot;logicquot; %> 5 6 <html> 7 <head><title>Submit example</title></head> 8 <body> 9 10 <h3>Example Submit Page</h3> 11 12 <html:errors/> 13 14 <html:form action=quot;submit.doquot;> 15 Last Name: <html:text property=quot;lastNamequot;/><br> 16 Address: <html:textarea property=quot;addressquot;/><br> 17 Sex: <html:radio property=quot;sexquot; value=quot;Mquot;/>Male 18 <html:radio property=quot;sexquot; value=quot;Fquot;/>Female<br> 19 Married: <html:checkbox property=quot;marriedquot;/><br> 20 Age: <html:select property=quot;agequot;> 21 <html:option value=quot;aquot;>0-19</html:option> 22 <html:option value=quot;bquot;>20-49</html:option> 23 <html:option value=quot;cquot;>50-</html:option> 30 24 </html:select><br>
  • 31. Example: ApplicationResources.properties 1 errors.header= <h4> Validation Error(s)</h4><ul> 2 3 error.lastName=<li>Enter your last name 4 error.address= <li>Enter your address 5 error.sex= <li>Enter your sex 6 error.age=<li>Enter your age 7 error.birthYear=<li>Enter the year you were born between 1900 and 2004 inclusive 8 9 errors.footer= </ul><hr> 31
  • 32. <html:messages/> ? Corrects the problem of <html:errors/> – Allows you to keep HTML tags in JSP pages not in the resource file ? By default, it looks for error messages stored in the request scope ? The id attribute defines the name of the scripting variable used to expose the error message text 32 .
  • 34. Logic Tags ? Provides presentation logic tags that eliminate need for scriptlets ? Value comparisons Include: = != <= >= < > ? Substring matching – match, notmatch ? Presentation logic – forward, redirect ? Collections – iterate 34 The quot;struts-logicquot; tag library contains tags that are useful in managing conditional generation of output text, looping over object collections for repetitive generation of output text, and application flow management
  • 35. Logic Tags ? <logic:present/> ? <logic:equal/> 35 .
  • 36. <logic:present/> & <logic:notPresent> tags ? The body of the <logic:present/> tag is evaluated whenever the JavaBean, or its property, is present within the JSP page ? Attributes for evaluation – name – parameter – cookie – header – property 36 .
  • 37. Example: submit.jsp 1 <logic:present name=quot;lastNamequot; scope=quot;requestquot;> 2 Hello 3 <logic:equal name=quot;submitFormquot; property=quot;agequot; value=quot;aquot;> 4 young 5 </logic:equal> 6 <logic:equal name=quot;submitFormquot; property=quot;agequot; value=quot;cquot;> 7 old 8 </logic:equal> 9 <bean:write name=quot;lastNamequot; scope=quot;requestquot;/> 10 </logic:present> 11 12 </body> 13 </html> < 37
  • 38. <logic:equal/> & <logic:notEqual> tags ? Checks against a specific value in a bean ? Assumes the bean exists – Exception occurs if not ? <logic:equal/> tag compares the bean's toString() value aganst the value property ? If property attribute is specified, then the value attribute is compared against the bean's property 38 .
  • 39. Example: submit.jsp 1 <logic:present name=quot;lastNamequot; scope=quot;requestquot;> 2 Hello 3 <logic:equal name=quot;submitFormquot; property=quot;agequot; value=quot;aquot;> 4 young 5 </logic:equal> 6 <logic:equal name=quot;submitFormquot; property=quot;agequot; value=quot;cquot;> 7 old 8 </logic:equal> 9 <bean:write name=quot;lastNamequot; scope=quot;requestquot;/> 10 </logic:present> 11 12 </body> 13 </html> < 39
  • 40. Usage Example: <logic:equal/> & <logic:notEqual> tags ? You want to present different messages or buttons on a page depending upon the type of action you migt perform ? Example: – Depending what a user wants to do (mode) – view, edit, or delete, you want to present different set of buttons – View mode: Show only view button – Edit mode: Show view and edit buttons – Delete mode: Show only delete button 40 .
  • 41. Example: subscription.jsp (ch 13) 1 <html:html> 2 <head> 3 <logic:equal name=quot;SubscriptionFormquot; property=quot;actionquot; 4 scope=quot;requestquot; value=quot;Createquot;> 5 <title><bean:message key=quot;subscription.title.createquot;/></title> 6 </logic:equal> 7 <logic:equal name=quot;SubscriptionFormquot; property=quot;actionquot; 8 scope=quot;requestquot; value=quot;Deletequot;> 9 <title><bean:message key=quot;subscription.title.deletequot;/></title> 10 </logic:equal> 11 <logic:equal name=quot;SubscriptionFormquot; property=quot;actionquot; 12 scope=quot;requestquot; value=quot;Editquot;> 13 <title><bean:message key=quot;subscription.title.editquot;/></title> 14 </logic:equal> 15 <html:base/> < 41
  • 43. Template Tags ? Templates are JSP pages that include parameterized content ? Useful for creating dynamic JSP templates for pages that share a common format ? Functionality provided is similar to what can be achieved using the standard JSP include directive, but these tags allow for dynamic rather than static content 43
  • 44. Template Tags ? Three template tags work in an interrelated function: – Get - Gets the content from request scope that was put there by a put tag. – Insert - Includes a template – Put - Puts content into request scope 44
  • 45. Template sample (insert/put) <template:insert template='/layout.jsp'> <template:put name='title' content='CD Manager Logon‘/> <template:put name='header' content='/header.jsp' /> <template:put name='content‘ content='/logonContent.jsp'/> <template:put name='footer' content='/footer.jsp' /> </template:insert> 45
  • 46. layout.jsp <html> <head> <title> <template:get name='title'/> </title> </head> <body > <table> <tr><td> <template:get name='header'/> </td></tr> <tr><td> <template:get name='content'/> </td></tr> <tr><td> <template:get name='footer'/> </td></tr> </table> </body> </html> 46
  • 47. Struts and JSTL 47
  • 48. When to JSTL in your Struts application? ? Developers should evaluate when to use the JSTL ? Many of the Struts taglib features are now available in the JSTL ? It’s simple: If the tag exists in the JSTL – use it ? Continue using the Struts tags where appropriate, they will continue to be supported 48 Some of the features in this taglib are also available in the JavaServer Pages Standard Tag Library (JSTL). The Struts team encourages the use of the standard tags over the Struts specific tags when possible.
  • 49. Interaction with JSTL ? Struts-el taglibs allow for using expression values instead of just rtexprvalue Runtime: <bean:message key='<%= stringvar %>'/> Expression: <bean-el:message key=quot;${stringvar}quot;/> ? Set of optional taglibs that can be used with the JSTL expression language (EL) ? Implements many (but not all) of the Struts tags. ? Located in the contrib folder of the Struts release ? Container with servlet 2.3 support required 49
  • 51. Struts EL Extension ? Extension of the Struts tag library ? Uses the expression evaluation engine in the Jakarta Taglibs implementation of the JSP Standard Tag Library (version 1.0) to evaluate attribute values ? Some of the Struts tags were not ported to this library – their functionality was entirely supplied by the JSTL This subprojectRequires theof the Struts tag library. Each JSP custom tag in this is an extension use of the Struts tag library, and ? library is a subclass of an associated Pages Standardlibrary.Library the Java Server tag in the Struts tag Tag One difference is 51 that this tag library does not use quot;rtexprvaluesquot;, it uses the expression evaluation engine in the Jakarta Taglibs implementation of the JSP Standard Tag Library (version 1.0) to evaluate attribute values. In addition, some of the Struts tags were not ported to this library, as it was determined that their functionality was entirely supplied by the JSTL. These particular Struts tags, and the reason for their non-porting will be described in the documentation for this library. In order to fully understand the correct utilization of this library, you must understand the use and operation of the Struts tag library, and the use and operation of the JavaServer Pages Standard Tag Library (hereafter called the quot;JSTLquot;), along with the expression language (sometimes called the quot;ELquot;) used for evaluating attribute values. The Struts-EL tag library requires the use of the Struts tag library, and the Java Server Pages Standard Tag Library. It is not necessary for JSP pages using the Struts- EL tag library to also use the Struts tags or the JSTL tags, but the Struts and JSTL tag libraries need to be part of the application utilizing the Struts-EL tag library. This is because the Struts-EL tag classes are all subclasses of Struts tag classes, and their implementation uses classes provided by the JSTL.
  • 52. Tag Mapping ? Every Struts tag that provides a feature that is not covered by the JSTL (1.0) library is mapped into the Struts-EL library ? Bean Tag Library Tags NOT Implemented in Struts-EL – cookie (in Struts): c:set, EL (in JSTL) – define (in Struts), c:set, EL (In JSTL) 52 In implementing the Struts-EL library, every Struts tag that provides a feature that is not covered by the JSTL (1.0) library is mapped into the Struts-EL library. This section reviews which Struts tags are NOT implemented in the Struts-EL library, and which JSTL tags provide that feature. Many of the non-porting decisions were based on the fact that the JSTL expression language itself provides the same functionality. In those cases, in addition to a possible JSTL tag name, the symbol quot;ELquot; will be listed.
  • 53. How to use Struts EL ? Struts – <bean:message key='<%= stringvar %>'/> ? Struts EL – <bean-el:message key=quot;${stringvar}quot;/> 53 The Struts-EL tag library is a contributed library in the Struts distribution. It represents an integration of the Struts tag library with the JavaServer Pages Standard Tag Library, or at least the quot;expression evaluationquot; engine that is used by the JSTL. The base Struts tag library contains tags which rely on the evaluation of quot;rtexprvaluequot;s (runtime scriptlet expressions) to evaluate dynamic attribute values. For instance, to print a message from a properties file based on a resource key, you would use the bean:write tag, perhaps like this: <bean:message key='<%= stringvar %>'/> This assumes that stringvar exists as a JSP scripting variable. If you're using the Struts-EL library, the reference looks very similar, but slightly different, like this: <bean-el:message key=quot;${stringvar}quot;/>
  • 55. Follow Good MVC Practice ? JSP pages must “know” as little as possible about the back-end architecture ? JSP page should only concern itself with rendering the view and not manipulating any data logic 55 .
  • 56. Passion! 56