SlideShare uma empresa Scribd logo
1 de 29
Baixar para ler offline
© 2010 Marty Hall




              Using JavaBeans
                  g
                   in JSP
               Originals of Slides and Source Code for Examples:
        http://courses.coreservlets.com/Course-Materials/csajsp2.html

                   Customized Java EE Training: http://courses.coreservlets.com/
     Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
2     Developed and taught by well-known author and developer. At public venues or onsite at your location.




                                                                                           © 2010 Marty Hall




    For live Java EE training, please see training courses
              at http://courses.coreservlets.com/.
      Servlets, JSP, Struts, JSF 1.x, JSF 2.0, Ajax (with jQuery, Dojo,
      Prototype, Ext-JS, Google Closure, etc.), GWT 2.0 (with GXT),
     Java 5, Java 6, SOAP-based and RESTful Web Services, Spring,    g
         Hibernate/JPA, and customized combinations of topics.
              Taught by the author of Core Servlets and JSP, More
             Servlets and JSP and this tutorial. Available at public
                                      JSP,                  tutorial
        venues, or customized versions can be held on-site at your
                     Customized Java EE Training: http://courses.coreservlets.com/
          organization. Contact hall@coreservlets.com for details.
     Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
      Developed and taught by well-known author and developer. At public venues or onsite at your location.
Agenda
    • Understanding the benefits of beans
         – We will use standalone beans here. Later sections will
           cover beans with MVC and the JSP expression language.
    • Creating beans
    • Installing bean classes on your server
    • Accessing bean properties
    • Explicitly setting bean properties
    • Automatically setting bean properties from
      request parameters
    • Sharing beans among multiple servlets and
      JSP pages
4




        Uses of JSP Constructs

                • Scripting elements calling servlet
      Simple      code directly
    Application
                • Scripting elements calling servlet
                           g               g
                  code indirectly (by means of utility
                  classes)
                • B
                  Beans
                • Servlet/JSP combo (MVC)
                • MVC with JSP expression language
                         ith             i l
     Complex • Custom tags
    Application • MVC with beans, custom tags, and
                         ith b         t   t         d
                  a framework like Struts or JSF
5
Background: What Are Beans?
    • Java classes that follow certain conventions
      – Must have a zero-argument (empty) constructor
         • You can satisfy this requirement either by explicitly
           defining such a constructor or by omitting all constructors
                  g                        y        g
      – Should have no public instance variables (fields)
         • You should already follow this practice and use accessor
           methods instead of allowing direct access to fields
      – Persistent values should be accessed through methods
        called getXxx and setXxx
         • If class has method getTitle that returns a String, class is
           said to have a String property named title
         • Boolean properties may use isXxx instead of getXxx
         • It is the name of the method, not instance var that matters!
      – For more on beans, see http://java.sun.com/beans/docs/
6




    More on Bean Properties
    • Usual rule to turn method name into
      property name
      – Drop the word “get” or “set” and change the next letter to
        lowercase. Again, instance var name is irrelevant.
         • Method name: getUserFirstName
         • Property name: userFirstName
    • Exception 1: boolean properties
          p                p p
      – If getter returns boolean or Boolean
         • Method name: getPrime or isPrime
         • Property name: prime
    • Exception 2: consecutive uppercase letters
      – If two uppercase letters in a row after “get” or “set”
         • M th d name: getURL
           Method          tURL
         • Property name: URL (not uRL)
7
Bean Properties: Examples
    Method Names               Property Name                           Example JSP Usage
    getFirstName                       firstName                       <jsp:getProperty … property="firstName"/>
    setFirstName                                                       <jsp:setProperty … property="firstName"/>
                                                                       ${customer.firstName}

    isExecutive                        executive                       <jsp:getProperty … property="executive"/>
    setExecutive                                                       <jsp:setProperty … property="executive"/>
    (boolean property)                                                 ${customer.executive}

    getExecutive                       executive                       <jsp:getProperty … property="executive"/>
    setExecutive                                                       <jsp:setProperty … property="executive"/>
    (boolean property)                                                 ${customer.executive}

    getZIP                                   ZIP                       <jsp:getProperty … property="ZIP"/>
    setZIP                                                             <jsp:setProperty … property="ZIP"/>
                                                                       ${address.ZIP}

                   Note 1: property name does not exist anywhere in your code. It is just a shortcut for the method name.
                   Note 2: property name is derived only from method name. Instance variable name is irrelevant.

8




     Why You Should Use
     Accessors,
     Accessors Not Public Fields
    • To be a bean, you cannot have public fields
    • So, you should replace
        public double speed;
    • with
                                                                     Note: in Eclipse, after you create instance variable, if you R-click and choose “Source”,
        private double speed;                                        it gives you option to generate getters and setters for you.



        public d bl getSpeed() {
          bli double          d()
          return(speed);
        }
        public void setSpeed(double newSpeed) {
          bli    id   tS    d(d bl     S   d)
          speed = newSpeed;
        }
    • Y
      You should do this in all your J
           h ld d thi i ll           Java code
                                            d
      anyhow. Why?
9
Why You Should Use
     Accessors,
     Accessors Not Public Fields
     • 1) You can put constraints on values
       public void setSpeed(double newSpeed) {
         if (newSpeed < 0) {
           sendErrorMessage(...);
           newSpeed = Math.abs(newSpeed);
         }
         speed = newSpeed;
       }

       – If users of your class accessed the fields directly, then
         they would each be responsible for checking constraints.


10




     Why You Should Use
     Accessors,
     Accessors Not Public Fields
     • 2) You can change your internal
       representation without changing interface
                  i    ih      h   i   i    f
       // Now using metric units ( p , not mph)
                  g              (kph,      p )

       public void setSpeed(double newSpeed) {
         speedInKPH = convert(newSpeed);
       }

       public oid setSpeedInKPH(double newSpeed)
       p blic void setSpeedInKPH(do ble ne Speed) {
         speedInKPH = newSpeed;
       }


11
Why You Should Use
     Accessors,
     Accessors Not Public Fields
     • 3) You can perform arbitrary side effects
       public double setSpeed(double newSpeed) {
         speed = newSpeed;
         updateSpeedometerDisplay();
       }

       – If users of your class accessed the fields directly, then
         they would each be responsible for executing side effects.
         Too much work and runs huge risk of having display
         inconsistent from actual values.



12




     Using Beans: Basic Tasks
     • jsp:useBean
       – I the simplest case, this element b ild a new bean.
         In h i l              hi l        builds      b
         It is normally used as follows:
          • <jsp:useBean id="beanName" class="package.Class" />
     • jsp:setProperty
       – This element modifies a bean property (i.e., calls a
         setBlah method). It is normally used as follows:
          • <jsp:setProperty name="beanName"
                             property="propertyName"
                             value="propertyValue" />
                                    p p y
     • jsp:getProperty
       – This element reads and outputs the value of a bean
         property.
         property It is used as follows:
          • <jsp:getProperty name="beanName"
                             property="propertyName" />
13
General Approach with Standalone
     Pages and jsp:useBean Tags
     • Input form
       – User submits form that refers to a JSP page
          • <FORM ACTION="SomePage.jsp">
     • JSP Page
       – JSP page instantiates a bean
          • <jsp:useBean id="myBean" class="…"/>
             j                y
       – You pass some request data to the bean
          • <jsp:setProperty name="myBean"
                             property customerID
                             property="customerID"
                             value="…"/>
       – You output some value(s) derived from the request data
          • <jsp:getProperty name="myBean"
                             name= myBean
                             property="bankAccountBalance"/>
14




     Building Beans: jsp:useBean
     • Format
       – <jsp:useBean id="name" class="package.Class" />
     • Purpose
       – All instantiation of Java classes without explicit Java
         Allow i    i i     fJ      l       ih        li i J
         programming (XML-compatible syntax)
     • Notes
       – Simple interpretation:
         <jsp:useBean id="book1" class="coreservlets.Book" />
             can be thought of as equivalent to the scriptlet
         <% coreservlets.Book book1 = new coreservlets.Book(); %>
       – But jsp:useBean has two additional advantages:
          • It is easier to derive object values from request parameters
          • It is easier to share objects among pages or servlets
15
Setting Simple Bean Properties:
     jsp:setProperty
     • Format
       – <jsp:setProperty name="name"
                          property="property"
                          value value /
                          value="value" />
     • Purpose
       – Allow setting of bean properties (i.e., calls to setXxx
                     g         p p        (
         methods) without explicit Java programming
     • Notes
       – <jsp:setProperty name="book1"
          j      P              "b k1"
                   property="title"
                   value="Core Servlets and JavaServer Pages" />
            is
            i equivalent to the following scriptlet
                 i l         h f ll i        i l
         <% book1.setTitle("Core Servlets and JavaServer Pages"); %>
16




     Accessing Bean Properties:
     jsp:getProperty
     • Format
       – <jsp:getProperty name="name" property="property" />
     • Purpose
       – All access to bean properties (i.e., calls to getXxx
         Allow          b            i (i       ll        X
         methods) without explicit Java programming
     • Notes
       – <jsp:getProperty name="book1" property="title" />
            is equivalent to the following JSP expression
                q                        g       p
         <%= book1.getTitle() %>



17
Example: StringBean
     package coreservlets;
     public class StringBean {
       private String message = "No message specified";
         public String getMessage() {
           return(message);
         }
         public void setMessage(String message) {
           this.message = message;
            hi
         }
     }
     • Beans installed in normal Java directory
          – MyEclipse: src/folderMatchingPackage
          – Deployment: WEB-INF/classes/folderMatchingPackage
              p y                         f          g     g
     • Beans must always be in packages!
18




         JSP Page That Uses StringBean
         (Code)
     <jsp:useBean id="stringBean"
                   class="coreservlets.StringBean" />
                                            g      /
     <OL>
     <LI>Initial value (from jsp:getProperty):
          <I><jsp:getProperty name="stringBean"
                              property="message" /></I>
     <LI>Initial value (from JSP expression):
          <I><%= stringBean.getMessage() %></I>
     <LI><jsp:setProperty name="stringBean"
                           property="message"
                           value="Best string bean: Fortex" />
          Value after setting property with jsp:setProperty:
          <I><jsp:getProperty name="stringBean"
                              name= stringBean
                              property="message" /></I>
     <LI><% stringBean.setMessage
                ("My favorite: Kentucky Wonder"); %>
          Value after setting property with scriptlet:
          <I><%= stringBean.getMessage() %></I>
     </OL>
19
JSP Page That Uses StringBean
      (Result)




20




      Setting Bean Properties Case 1:
      Explicit Conversion & Assignment
     <!DOCTYPE ...>
     ...
     <jsp:useBean id="entry"
                  class="coreservlets.SaleEntry" />

     <%-- setItemID expects a String --%>

     <jsp:setProperty
      j p        p   y
          name="entry"
          property="itemID"
          value='<%= request.getParameter("itemID") %>' />
                       q     g




21
Setting Bean Properties Case 1:
       Explicit Conversion & Assignment
     <%
     int numItemsOrdered = 1;
     try {
        numItemsOrdered =
          Integer.parseInt(request.getParameter( numItems ));
          Integer parseInt(request getParameter("numItems"));
     } catch(NumberFormatException nfe) {}
     %>

     <%-- setNumItems expects an int --%>

     <jsp:setProperty
      jsp:set ope ty
         name="entry"
         property="numItems"
         value="<%= numItemsOrdered %>" />
                                        /


22




       Setting Bean Properties Case 1:
       Explicit Conversion & Assignment
      <%
      double discountCode = 1 0;
                             1.0;
      try {
         String discountString =
           request.getParameter( discountCode );
           request getParameter("discountCode");
         discountCode =
           Double.parseDouble(discountString);
      } catch(NumberFormatException nfe) {}
      %>

      <%-- setDiscountCode e pects a doub e --%>
       %   set scou tCode expects    double   %

      <jsp:setProperty
                    y
          name="entry"
          property="discountCode"
          value="<%= discountCode %>" />
23
Setting Bean Properties Case 1:
     Explicit Conversion & Assignment




24




     Case 2: Associating Individual
     Properties with Input Parameters
     • Use the param attribute of jsp:setProperty
       to i di
          indicate that
                    h
       – Value should come from specified request parameter
       – Simple automatic type conversion should be performed
         for properties that expect values of standard types
          • boolean, Boolean, byte, Byte, char, Character, double,
            Double, i t I t
            D bl int, Integer, float, Float, long, or Long.
                               fl t Fl t l            L




25
Case 2: Associating Individual
     Properties with Input Parameters
     <jsp:useBean id="entry"
                  class="coreservlets.SaleEntry"
                  class="coreservlets SaleEntry" />
     <jsp:setProperty
         name="entry"
         property="itemID"
         param="itemID" />
     <jsp:setProperty
         name="entry"
         property="numItems"
         p
         param="numItems" />
                           /
     <jsp:setProperty
         name="entry"
         property= discountCode
         property="discountCode"
         param="discountCode" />
26




     Case 3: Associating All Properties
     with Input Parameters
     • Use "*" for the value of the property
       attribute of j
           ib     f jsp:setProperty to indicate that
                           P           i di      h
       – Value should come from request parameter whose name
         matches property name
       – Simple automatic type conversion should be performed




27
Case 3: Associating All Properties
     with Input Parameters
     <jsp:useBean id="entry"
                  class="coreservlets.SaleEntry" />
                   l    "        l t S l E t "
     <jsp:setProperty name="entry" property="*" />

     • This is extremely convenient for making
       "form beans" -- objects whose properties
       are fill d in from a form submission.
           filled i f       f      b i i
       – You can even divide the process up across multiple
         forms, where each submission fills in part of the object.




28




     Sharing Beans
     • You can use the scope attribute to specify
       additional places where bean is stored
        ddi i   l l       h    b    i       d
       – Still also bound to local variable in _jspService
       – <jsp:useBean id=" " class=" "
                        id="…" class="…"
                        scope="…" />
     • Lets multiple servlets or JSP pages
                 p                   p g
       share data
     • Also permits conditional bean creation
       – Creates new object only if it can't find existing one



29
Sharing Beans: Example
     • page1.jsp
       <jsp:useBean id "f " class="…" scope="application"/>
        j      B     id="foo" l    " "        " li i "/
       <jsp:setProperty name="foo" property="message"
                        value="Hello"/>
       <jsp:getProperty name="foo" property="message"/>
     • page2.jsp
       <jsp:useBean id="foo" class="…" scope="application"/>
        jp                                 p   pp
       <jsp:getProperty name="foo" property="message"/>
     • Possible scenario 1
       – J goes t page 2 ( t t is "Default Message")
         Joe     to         (output i "D f lt M   ")
       – Jane goes to page 1 (output is "Hello")
     • Possible scenario 2
       – Joe goes to page 1 (output is "Hello")
       – Jane goes to page 2 (output is "Hello")
30




     Values of the scope Attribute
     • page (<jsp:useBean … scope="page"/> or
             <jsp:useBean…>)
              j      B      )
       – Default value. Bean object should be placed in the
         PageContext object for the duration of the current
         request. Lets methods in same servlet access bean
     • application
       (<jsp:useBean … scope="application"/>)
       – Bean will be stored in ServletContext (available through
         the application variable or by call to getServletContext()).
                                                getServletContext())
         ServletContext is shared by all servlets in the same Web
         application (or all servlets on server if no explicit Web
         applications are defined).
             li i         d fi d)

31
Values of the scope Attribute
     • session
        (<jsp:useBean … scope="session"/>)
        ( j      B            "    i "/ )
          – Bean will be stored in the HttpSession object associated
            with the current request, where it can be accessed from
                             request
            regular servlet code with getAttribute and setAttribute, as
            with normal session objects.
     • request
        (<jsp:useBean … scope="request"/>)
          – Bean object should be placed in the ServletRequest object
            for the duration of the current request, where it is
            available by means of getAttribute


32




         Sharing Beans in Four Different
         Ways
     •   Using unshared (page-scoped) beans.
     •   Sharing request-scoped beans.
     •   Sharing session-scoped beans.
     •   Sharing application-scoped (i.e.,
         ServletContext-scoped) beans.




     • Important:
          – Use different names (i.e., id in jsp:useBean) for different
                                (i e
            beans
33           • Don't store beans in different places with same id
Sharing Beans Four Ways:
     Bean Code
     package coreservlets;
     …
     public class BakedBean implements Serializable {
       private String level = "half-baked";
       private String goesWith = "hot dogs";

         public String getLevel() {
           return(level);
         }
         public void setLevel(String newLevel) {
           level = newLevel;
         }
         public String getGoesWith() {
           return(goesWith);
         }
         public void setGoesWith(String dish) {
           goesWith = dish;
         }
34   }




     Sharing Beans Example 1:
     Page-Scoped (Unshared)
     • Create the bean
         – Use jsp:useBean with scope="page" (or no scope at all,
           since page is the default).
     • Modify the bean
         – Use jsp:setProperty with property="*".
         – Then, supply request parameters that match the bean
                , pp y q        p
           property names.
     • Access the bean
         – Use jsp:getProperty.



35
Sharing Beans Example 1:
     Page-Scoped (Unshared)
     …
     <BODY>
     <H1>Baked Bean Values: page-based Sharing</H1>
     <jsp:useBean id="pageBean"
                  class="coreservlets.BakedBean"
                  class="coreservlets BakedBean" />
     <jsp:setProperty name="pageBean" property="*" />
     <H2>Bean level:
     <jsp:getProperty name="pageBean"
     <j     tP      t      "    B   "
                      property="level" />
     </H2>
     <H2>Dish bean goes with:
       2
     <jsp:getProperty name="pageBean"
                      property="goesWith" />
     </H2>
     </BODY></HTML>
36




     Sharing Beans Example 1:
     Result (Initial Request)




37
Sharing Beans Example 1:
     Result (Later Request)




38




     Sharing Beans Example 2:
     Request-Based Sharing
     • Create the bean
       –U j
        Use jsp:useBean with scope="request".
                   B     ith       "      t"
     • Modify the bean
       – Use jsp:setProperty with property="*".
             jp        p y        p p y
       – Then, supply request parameters that match the bean
         property names.
     • Access the bean in the 1st (main) page
       – Use jsp:getProperty.
       – Then, use jsp:include to invoke the second page.
     • Access the bean in the 2nd (included) page
       – Use jsp:useBean with the same id as on the first page,
         again with scope request .
                    scope="request".
       – Then, use jsp:getProperty.
39
Request-Based Sharing:
      Code for Main Page
     …
     <BODY>
     <H1>Baked Bean Values: request-based Sharing</H1>
     <jsp:useBean id="requestBean"
                  class= coreservlets.BakedBean
                  class="coreservlets BakedBean"
                  scope="request" />
     <jsp:setProperty name="requestBean"
                      property
                      property="*" />
     <H2>Bean level:
     <jsp:getProperty name="requestBean"
                      p ope ty
                      property="level" / /
                                  e e  /></H2>
     <H2>Dish bean goes with:
     <jsp:getProperty name="requestBean"
                      p p
                      property="goesWith" / /
                              y g         /></H2>
     <jsp:include page=
       "/WEB-INF/includes/BakedBeanDisplay-snippet.jsp"/>
40   </BODY></HTML>




      Request-Based Sharing:
      Code for Included Page
     <H1>Repeated Baked Bean Values:
     request-based Sharing</H1>
     <jsp:useBean id="requestBean"
                  class="coreservlets.BakedBean"
                  scope="request" />
     <H2>Bean level:
     <jsp:getProperty name="requestBean"
                      property="level" />
                            t "l     l"
     </H2>
     <H2>Dish bean goes with:
     <jsp:getProperty name="requestBean"
                      property="goesWith" />
     </H2>


41
Request-Based Sharing:
     Result (Initial Request)




42




     Request-Based Sharing:
     Result (Later Request)




43
Sharing Beans Example 3:
     Session-Based Sharing
     • Create the bean
       – U j
         Use jsp:useBean with scope="session".
                    B     ih        "    i "
     • Modify the bean
       – Use jsp:setProperty with property="*".
             jp        p y        p p y
       – Then, supply request parameters that match the bean property
         names.
     • Access the bean in the initial request
       – Use jsp:getProperty in the request in which jsp:setProperty is
         invoked.
     • Access the bean later
       – Use jsp:getProperty in a request that does not include request
         parameters and thus does not invoke jsp:setProperty. If this request
         is from the same client (within the session timeout), the previously
                                                       timeout)
         modified value is seen. If this request is from a different client (or
         after the session timeout), a newly created bean is seen.
44




     Session-Based Sharing: Code
     …
     <BODY>
     <H1>Baked Bean Values: session-based Sharing</H1>
     <jsp:useBean id="sessionBean"
                  class="coreservlets.BakedBean"
                  class="coreservlets BakedBean"
                  scope="session" />
     <jsp:setProperty name="sessionBean"
                      property="*" />
                            t "*"
     <H2>Bean level:
     <jsp:getProperty name="sessionBean"
                      property="level" /
                                       />
     </H2>
     <H2>Dish bean goes with:
     <jsp:getProperty name="sessionBean"
                      property="goesWith" />
45   </H2></BODY></HTML>
Session-Based Sharing: Result
     (Initial Request)




46




     Session-Based Sharing: Result
     (Later Request -- Same Client)




47
Session-Based Sharing: Result
     (Later Request -- New Client)




48




     Sharing Beans Example 4:
     Application-Based Sharing
     • Create the bean
       – U j
         Use jsp:useBean with scope="application".
                    B     ih        " li i "
     • Modify the bean
       – Use jsp:setProperty with property="*".
             jp        p y        p p y
       – Then, supply request parameters that match the bean property
         names.
     • Access the bean in the initial request
       – Use jsp:getProperty in the request in which jsp:setProperty is
         invoked.
     • Access the bean later
       – Use jsp:getProperty in a request that does not include request
         parameters and thus does not invoke jsp:setProperty. Whether this
         request is from the same client or a different client (regardless of the
         session timeout), the previously modified value is seen.
49
Application-Based Sharing:
     Code
     <BODY>
     <H1>Baked Bean Values:
     application-based Sharing</H1>
     <jsp:useBean id="applicationBean"
                  class="coreservlets.BakedBean"
                  class="coreservlets BakedBean"
                  scope="application" />
     <jsp:setProperty name="applicationBean"
                      property="*" />
                            t "*"
     <H2>Bean level:
     <jsp:getProperty name="applicationBean"
                      property="level" /
                                       />
     </H2>
     <H2>Dish bean goes with:
     <jsp:getProperty name="applicationBean"
                      property="goesWith"/>
50   </H2></BODY></HTML>




     Application-Based Sharing:
     Result (Initial Request)




51
Application-Based Sharing: Result
     (Later Request -- Same Client)




52




     Application-Based Sharing: Result
     (Later Request -- New Client)




53
Conditional Bean Operations
     • Bean conditionally created
          – jsp:useBean results in new bean being instantiated only if
            no bean with same id and scope can be found.
          – If a bean with same id and scope is found, the preexisting
                                                found
            bean is simply bound to variable referenced by id.
     • Bean properties conditionally set
            p p                    y
          – <jsp:useBean ... />
            replaced by
            <jsp:useBean ...>statements</jsp:useBean>
                            >statements</jsp:useBean>
          – The statements (jsp:setProperty elements) are executed
            only if a new bean is created, not if an existing bean is
            found.

54




         Conditional Bean Creation:
         AccessCountBean
     public class AccessCountBean {
       p
       private String firstPage;
                    g        g
       private int accessCount = 1;

         public String getFirstPage() {
           return(firstPage);
         }

         public void setFirstPage(String firstPage) {
           this.firstPage
           this firstPage = firstPage;
         }

         public int getAccessCount() {
           return(accessCount);
             t   (      C   t)
         }

         public void setAccessCountIncrement(int increment) {
           accessCount = accessCount + increment;
         }
     }
55
Conditional Bean Creation:
      SharedCounts1.jsp
      SharedCounts1 jsp
     <jsp:useBean id="counter"
                  class="coreservlets.AccessCountBean"
                  scope="application">
       <jsp:setProperty name="counter"
                         property="firstPage"
                         value SharedCounts1.jsp
                         value="SharedCounts1.jsp" />
     </jsp:useBean>
     Of SharedCounts1.jsp (this page),
     <A HREF="SharedCounts2.jsp">SharedCounts2.jsp</A>, and
     <A HREF="SharedCounts3 jsp">SharedCounts3 jsp</A>
        HREF="SharedCounts3.jsp">SharedCounts3.jsp</A>,
     <jsp:getProperty name="counter" property="firstPage" />
     was the first page accessed.
     <P>
     Collectively, th th
     C ll ti l      the three pages h
                                    have b
                                         been accessed
                                                     d
     <jsp:getProperty name="counter" property="accessCount" />
     times.
     <jsp:setProperty name="counter"
                       property="accessCountIncrement"
                       value="1" />
56




      Accessing SharedCounts1,
      SharedCounts2,
      SharedCounts2 SharedCounts3
     • SharedCounts2.jsp was accessed first.
     • Pages have been accessed twelve previous
       times by an arbitrary number of clients




57
Summary
     • Benefits of jsp:useBean
       – Hides the Java syntax
       – Makes it easier to associate request parameters with Java
         objects (bean properties)
       – Simplifies sharing objects among multiple requests or
         servlets/JSPs
     • j
       jsp:useBean
              B
       – Creates or accesses a bean
     • jsp:setProperty
       – Sets bean property (i.e. passes value to setXxx)
          • You usually use p p y
                      y     property="*" to p
                                            pass in request params
                                                      q     p
     • jsp:getProperty
58
       – Puts bean property (i.e. getXxx call) into servlet output



                                                                                               © 2010 Marty Hall




                                Questions?

                       Customized Java EE Training: http://courses.coreservlets.com/
         Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
59        Developed and taught by well-known author and developer. At public venues or onsite at your location.

Mais conteúdo relacionado

Mais procurados (20)

Unit iv
Unit ivUnit iv
Unit iv
 
Java beans
Java beansJava beans
Java beans
 
Javabeans .pdf
Javabeans .pdfJavabeans .pdf
Javabeans .pdf
 
Javabean1
Javabean1Javabean1
Javabean1
 
Bean Intro
Bean IntroBean Intro
Bean Intro
 
Java beans
Java beansJava beans
Java beans
 
Java Beans
Java BeansJava Beans
Java Beans
 
Java beans
Java beansJava beans
Java beans
 
Java beans
Java beansJava beans
Java beans
 
Jsp Introduction Tutorial
Jsp Introduction TutorialJsp Introduction Tutorial
Jsp Introduction Tutorial
 
enterprise java bean
enterprise java beanenterprise java bean
enterprise java bean
 
Ejb3.1 for the starter
Ejb3.1 for the starterEjb3.1 for the starter
Ejb3.1 for the starter
 
2007 Fsoss Drupal Under The Hood
2007 Fsoss Drupal Under The Hood2007 Fsoss Drupal Under The Hood
2007 Fsoss Drupal Under The Hood
 
Entity beans in java
Entity beans in javaEntity beans in java
Entity beans in java
 
Ejb3 Presentation
Ejb3 PresentationEjb3 Presentation
Ejb3 Presentation
 
Session bean
Session beanSession bean
Session bean
 
EJB .
EJB .EJB .
EJB .
 
Jsp session 6
Jsp   session 6Jsp   session 6
Jsp session 6
 
J2EE jsp_01
J2EE jsp_01J2EE jsp_01
J2EE jsp_01
 
Using java beans(ii)
Using java beans(ii)Using java beans(ii)
Using java beans(ii)
 

Semelhante a java beans (20)

13 java beans
13 java beans13 java beans
13 java beans
 
14 mvc
14 mvc14 mvc
14 mvc
 
Ajax Tags Advanced
Ajax Tags AdvancedAjax Tags Advanced
Ajax Tags Advanced
 
Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268
 
Json generation
Json generationJson generation
Json generation
 
JSP Part 2
JSP Part 2JSP Part 2
JSP Part 2
 
10 jdbc
10 jdbc10 jdbc
10 jdbc
 
10 jdbc
10 jdbc10 jdbc
10 jdbc
 
15 expression-language
15 expression-language15 expression-language
15 expression-language
 
Prototype-1
Prototype-1Prototype-1
Prototype-1
 
Prototype-1
Prototype-1Prototype-1
Prototype-1
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
 
02 servlet-basics
02 servlet-basics02 servlet-basics
02 servlet-basics
 
JavaScript Coding with Class
JavaScript Coding with ClassJavaScript Coding with Class
JavaScript Coding with Class
 
WEB TECHNOLOGIES JSP
WEB TECHNOLOGIES  JSPWEB TECHNOLOGIES  JSP
WEB TECHNOLOGIES JSP
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Gradle talk, Javarsovia 2010
Gradle talk, Javarsovia 2010Gradle talk, Javarsovia 2010
Gradle talk, Javarsovia 2010
 
JavaScript-Core
JavaScript-CoreJavaScript-Core
JavaScript-Core
 
JavaScript-Core
JavaScript-CoreJavaScript-Core
JavaScript-Core
 
Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS
 

Último

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 

Último (20)

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 

java beans

  • 1. © 2010 Marty Hall Using JavaBeans g in JSP Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/Course-Materials/csajsp2.html Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. 2 Developed and taught by well-known author and developer. At public venues or onsite at your location. © 2010 Marty Hall For live Java EE training, please see training courses at http://courses.coreservlets.com/. Servlets, JSP, Struts, JSF 1.x, JSF 2.0, Ajax (with jQuery, Dojo, Prototype, Ext-JS, Google Closure, etc.), GWT 2.0 (with GXT), Java 5, Java 6, SOAP-based and RESTful Web Services, Spring, g Hibernate/JPA, and customized combinations of topics. Taught by the author of Core Servlets and JSP, More Servlets and JSP and this tutorial. Available at public JSP, tutorial venues, or customized versions can be held on-site at your Customized Java EE Training: http://courses.coreservlets.com/ organization. Contact hall@coreservlets.com for details. Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.
  • 2. Agenda • Understanding the benefits of beans – We will use standalone beans here. Later sections will cover beans with MVC and the JSP expression language. • Creating beans • Installing bean classes on your server • Accessing bean properties • Explicitly setting bean properties • Automatically setting bean properties from request parameters • Sharing beans among multiple servlets and JSP pages 4 Uses of JSP Constructs • Scripting elements calling servlet Simple code directly Application • Scripting elements calling servlet g g code indirectly (by means of utility classes) • B Beans • Servlet/JSP combo (MVC) • MVC with JSP expression language ith i l Complex • Custom tags Application • MVC with beans, custom tags, and ith b t t d a framework like Struts or JSF 5
  • 3. Background: What Are Beans? • Java classes that follow certain conventions – Must have a zero-argument (empty) constructor • You can satisfy this requirement either by explicitly defining such a constructor or by omitting all constructors g y g – Should have no public instance variables (fields) • You should already follow this practice and use accessor methods instead of allowing direct access to fields – Persistent values should be accessed through methods called getXxx and setXxx • If class has method getTitle that returns a String, class is said to have a String property named title • Boolean properties may use isXxx instead of getXxx • It is the name of the method, not instance var that matters! – For more on beans, see http://java.sun.com/beans/docs/ 6 More on Bean Properties • Usual rule to turn method name into property name – Drop the word “get” or “set” and change the next letter to lowercase. Again, instance var name is irrelevant. • Method name: getUserFirstName • Property name: userFirstName • Exception 1: boolean properties p p p – If getter returns boolean or Boolean • Method name: getPrime or isPrime • Property name: prime • Exception 2: consecutive uppercase letters – If two uppercase letters in a row after “get” or “set” • M th d name: getURL Method tURL • Property name: URL (not uRL) 7
  • 4. Bean Properties: Examples Method Names Property Name Example JSP Usage getFirstName firstName <jsp:getProperty … property="firstName"/> setFirstName <jsp:setProperty … property="firstName"/> ${customer.firstName} isExecutive executive <jsp:getProperty … property="executive"/> setExecutive <jsp:setProperty … property="executive"/> (boolean property) ${customer.executive} getExecutive executive <jsp:getProperty … property="executive"/> setExecutive <jsp:setProperty … property="executive"/> (boolean property) ${customer.executive} getZIP ZIP <jsp:getProperty … property="ZIP"/> setZIP <jsp:setProperty … property="ZIP"/> ${address.ZIP} Note 1: property name does not exist anywhere in your code. It is just a shortcut for the method name. Note 2: property name is derived only from method name. Instance variable name is irrelevant. 8 Why You Should Use Accessors, Accessors Not Public Fields • To be a bean, you cannot have public fields • So, you should replace public double speed; • with Note: in Eclipse, after you create instance variable, if you R-click and choose “Source”, private double speed; it gives you option to generate getters and setters for you. public d bl getSpeed() { bli double d() return(speed); } public void setSpeed(double newSpeed) { bli id tS d(d bl S d) speed = newSpeed; } • Y You should do this in all your J h ld d thi i ll Java code d anyhow. Why? 9
  • 5. Why You Should Use Accessors, Accessors Not Public Fields • 1) You can put constraints on values public void setSpeed(double newSpeed) { if (newSpeed < 0) { sendErrorMessage(...); newSpeed = Math.abs(newSpeed); } speed = newSpeed; } – If users of your class accessed the fields directly, then they would each be responsible for checking constraints. 10 Why You Should Use Accessors, Accessors Not Public Fields • 2) You can change your internal representation without changing interface i ih h i i f // Now using metric units ( p , not mph) g (kph, p ) public void setSpeed(double newSpeed) { speedInKPH = convert(newSpeed); } public oid setSpeedInKPH(double newSpeed) p blic void setSpeedInKPH(do ble ne Speed) { speedInKPH = newSpeed; } 11
  • 6. Why You Should Use Accessors, Accessors Not Public Fields • 3) You can perform arbitrary side effects public double setSpeed(double newSpeed) { speed = newSpeed; updateSpeedometerDisplay(); } – If users of your class accessed the fields directly, then they would each be responsible for executing side effects. Too much work and runs huge risk of having display inconsistent from actual values. 12 Using Beans: Basic Tasks • jsp:useBean – I the simplest case, this element b ild a new bean. In h i l hi l builds b It is normally used as follows: • <jsp:useBean id="beanName" class="package.Class" /> • jsp:setProperty – This element modifies a bean property (i.e., calls a setBlah method). It is normally used as follows: • <jsp:setProperty name="beanName" property="propertyName" value="propertyValue" /> p p y • jsp:getProperty – This element reads and outputs the value of a bean property. property It is used as follows: • <jsp:getProperty name="beanName" property="propertyName" /> 13
  • 7. General Approach with Standalone Pages and jsp:useBean Tags • Input form – User submits form that refers to a JSP page • <FORM ACTION="SomePage.jsp"> • JSP Page – JSP page instantiates a bean • <jsp:useBean id="myBean" class="…"/> j y – You pass some request data to the bean • <jsp:setProperty name="myBean" property customerID property="customerID" value="…"/> – You output some value(s) derived from the request data • <jsp:getProperty name="myBean" name= myBean property="bankAccountBalance"/> 14 Building Beans: jsp:useBean • Format – <jsp:useBean id="name" class="package.Class" /> • Purpose – All instantiation of Java classes without explicit Java Allow i i i fJ l ih li i J programming (XML-compatible syntax) • Notes – Simple interpretation: <jsp:useBean id="book1" class="coreservlets.Book" /> can be thought of as equivalent to the scriptlet <% coreservlets.Book book1 = new coreservlets.Book(); %> – But jsp:useBean has two additional advantages: • It is easier to derive object values from request parameters • It is easier to share objects among pages or servlets 15
  • 8. Setting Simple Bean Properties: jsp:setProperty • Format – <jsp:setProperty name="name" property="property" value value / value="value" /> • Purpose – Allow setting of bean properties (i.e., calls to setXxx g p p ( methods) without explicit Java programming • Notes – <jsp:setProperty name="book1" j P "b k1" property="title" value="Core Servlets and JavaServer Pages" /> is i equivalent to the following scriptlet i l h f ll i i l <% book1.setTitle("Core Servlets and JavaServer Pages"); %> 16 Accessing Bean Properties: jsp:getProperty • Format – <jsp:getProperty name="name" property="property" /> • Purpose – All access to bean properties (i.e., calls to getXxx Allow b i (i ll X methods) without explicit Java programming • Notes – <jsp:getProperty name="book1" property="title" /> is equivalent to the following JSP expression q g p <%= book1.getTitle() %> 17
  • 9. Example: StringBean package coreservlets; public class StringBean { private String message = "No message specified"; public String getMessage() { return(message); } public void setMessage(String message) { this.message = message; hi } } • Beans installed in normal Java directory – MyEclipse: src/folderMatchingPackage – Deployment: WEB-INF/classes/folderMatchingPackage p y f g g • Beans must always be in packages! 18 JSP Page That Uses StringBean (Code) <jsp:useBean id="stringBean" class="coreservlets.StringBean" /> g / <OL> <LI>Initial value (from jsp:getProperty): <I><jsp:getProperty name="stringBean" property="message" /></I> <LI>Initial value (from JSP expression): <I><%= stringBean.getMessage() %></I> <LI><jsp:setProperty name="stringBean" property="message" value="Best string bean: Fortex" /> Value after setting property with jsp:setProperty: <I><jsp:getProperty name="stringBean" name= stringBean property="message" /></I> <LI><% stringBean.setMessage ("My favorite: Kentucky Wonder"); %> Value after setting property with scriptlet: <I><%= stringBean.getMessage() %></I> </OL> 19
  • 10. JSP Page That Uses StringBean (Result) 20 Setting Bean Properties Case 1: Explicit Conversion & Assignment <!DOCTYPE ...> ... <jsp:useBean id="entry" class="coreservlets.SaleEntry" /> <%-- setItemID expects a String --%> <jsp:setProperty j p p y name="entry" property="itemID" value='<%= request.getParameter("itemID") %>' /> q g 21
  • 11. Setting Bean Properties Case 1: Explicit Conversion & Assignment <% int numItemsOrdered = 1; try { numItemsOrdered = Integer.parseInt(request.getParameter( numItems )); Integer parseInt(request getParameter("numItems")); } catch(NumberFormatException nfe) {} %> <%-- setNumItems expects an int --%> <jsp:setProperty jsp:set ope ty name="entry" property="numItems" value="<%= numItemsOrdered %>" /> / 22 Setting Bean Properties Case 1: Explicit Conversion & Assignment <% double discountCode = 1 0; 1.0; try { String discountString = request.getParameter( discountCode ); request getParameter("discountCode"); discountCode = Double.parseDouble(discountString); } catch(NumberFormatException nfe) {} %> <%-- setDiscountCode e pects a doub e --%> % set scou tCode expects double % <jsp:setProperty y name="entry" property="discountCode" value="<%= discountCode %>" /> 23
  • 12. Setting Bean Properties Case 1: Explicit Conversion & Assignment 24 Case 2: Associating Individual Properties with Input Parameters • Use the param attribute of jsp:setProperty to i di indicate that h – Value should come from specified request parameter – Simple automatic type conversion should be performed for properties that expect values of standard types • boolean, Boolean, byte, Byte, char, Character, double, Double, i t I t D bl int, Integer, float, Float, long, or Long. fl t Fl t l L 25
  • 13. Case 2: Associating Individual Properties with Input Parameters <jsp:useBean id="entry" class="coreservlets.SaleEntry" class="coreservlets SaleEntry" /> <jsp:setProperty name="entry" property="itemID" param="itemID" /> <jsp:setProperty name="entry" property="numItems" p param="numItems" /> / <jsp:setProperty name="entry" property= discountCode property="discountCode" param="discountCode" /> 26 Case 3: Associating All Properties with Input Parameters • Use "*" for the value of the property attribute of j ib f jsp:setProperty to indicate that P i di h – Value should come from request parameter whose name matches property name – Simple automatic type conversion should be performed 27
  • 14. Case 3: Associating All Properties with Input Parameters <jsp:useBean id="entry" class="coreservlets.SaleEntry" /> l " l t S l E t " <jsp:setProperty name="entry" property="*" /> • This is extremely convenient for making "form beans" -- objects whose properties are fill d in from a form submission. filled i f f b i i – You can even divide the process up across multiple forms, where each submission fills in part of the object. 28 Sharing Beans • You can use the scope attribute to specify additional places where bean is stored ddi i l l h b i d – Still also bound to local variable in _jspService – <jsp:useBean id=" " class=" " id="…" class="…" scope="…" /> • Lets multiple servlets or JSP pages p p g share data • Also permits conditional bean creation – Creates new object only if it can't find existing one 29
  • 15. Sharing Beans: Example • page1.jsp <jsp:useBean id "f " class="…" scope="application"/> j B id="foo" l " " " li i "/ <jsp:setProperty name="foo" property="message" value="Hello"/> <jsp:getProperty name="foo" property="message"/> • page2.jsp <jsp:useBean id="foo" class="…" scope="application"/> jp p pp <jsp:getProperty name="foo" property="message"/> • Possible scenario 1 – J goes t page 2 ( t t is "Default Message") Joe to (output i "D f lt M ") – Jane goes to page 1 (output is "Hello") • Possible scenario 2 – Joe goes to page 1 (output is "Hello") – Jane goes to page 2 (output is "Hello") 30 Values of the scope Attribute • page (<jsp:useBean … scope="page"/> or <jsp:useBean…>) j B ) – Default value. Bean object should be placed in the PageContext object for the duration of the current request. Lets methods in same servlet access bean • application (<jsp:useBean … scope="application"/>) – Bean will be stored in ServletContext (available through the application variable or by call to getServletContext()). getServletContext()) ServletContext is shared by all servlets in the same Web application (or all servlets on server if no explicit Web applications are defined). li i d fi d) 31
  • 16. Values of the scope Attribute • session (<jsp:useBean … scope="session"/>) ( j B " i "/ ) – Bean will be stored in the HttpSession object associated with the current request, where it can be accessed from request regular servlet code with getAttribute and setAttribute, as with normal session objects. • request (<jsp:useBean … scope="request"/>) – Bean object should be placed in the ServletRequest object for the duration of the current request, where it is available by means of getAttribute 32 Sharing Beans in Four Different Ways • Using unshared (page-scoped) beans. • Sharing request-scoped beans. • Sharing session-scoped beans. • Sharing application-scoped (i.e., ServletContext-scoped) beans. • Important: – Use different names (i.e., id in jsp:useBean) for different (i e beans 33 • Don't store beans in different places with same id
  • 17. Sharing Beans Four Ways: Bean Code package coreservlets; … public class BakedBean implements Serializable { private String level = "half-baked"; private String goesWith = "hot dogs"; public String getLevel() { return(level); } public void setLevel(String newLevel) { level = newLevel; } public String getGoesWith() { return(goesWith); } public void setGoesWith(String dish) { goesWith = dish; } 34 } Sharing Beans Example 1: Page-Scoped (Unshared) • Create the bean – Use jsp:useBean with scope="page" (or no scope at all, since page is the default). • Modify the bean – Use jsp:setProperty with property="*". – Then, supply request parameters that match the bean , pp y q p property names. • Access the bean – Use jsp:getProperty. 35
  • 18. Sharing Beans Example 1: Page-Scoped (Unshared) … <BODY> <H1>Baked Bean Values: page-based Sharing</H1> <jsp:useBean id="pageBean" class="coreservlets.BakedBean" class="coreservlets BakedBean" /> <jsp:setProperty name="pageBean" property="*" /> <H2>Bean level: <jsp:getProperty name="pageBean" <j tP t " B " property="level" /> </H2> <H2>Dish bean goes with: 2 <jsp:getProperty name="pageBean" property="goesWith" /> </H2> </BODY></HTML> 36 Sharing Beans Example 1: Result (Initial Request) 37
  • 19. Sharing Beans Example 1: Result (Later Request) 38 Sharing Beans Example 2: Request-Based Sharing • Create the bean –U j Use jsp:useBean with scope="request". B ith " t" • Modify the bean – Use jsp:setProperty with property="*". jp p y p p y – Then, supply request parameters that match the bean property names. • Access the bean in the 1st (main) page – Use jsp:getProperty. – Then, use jsp:include to invoke the second page. • Access the bean in the 2nd (included) page – Use jsp:useBean with the same id as on the first page, again with scope request . scope="request". – Then, use jsp:getProperty. 39
  • 20. Request-Based Sharing: Code for Main Page … <BODY> <H1>Baked Bean Values: request-based Sharing</H1> <jsp:useBean id="requestBean" class= coreservlets.BakedBean class="coreservlets BakedBean" scope="request" /> <jsp:setProperty name="requestBean" property property="*" /> <H2>Bean level: <jsp:getProperty name="requestBean" p ope ty property="level" / / e e /></H2> <H2>Dish bean goes with: <jsp:getProperty name="requestBean" p p property="goesWith" / / y g /></H2> <jsp:include page= "/WEB-INF/includes/BakedBeanDisplay-snippet.jsp"/> 40 </BODY></HTML> Request-Based Sharing: Code for Included Page <H1>Repeated Baked Bean Values: request-based Sharing</H1> <jsp:useBean id="requestBean" class="coreservlets.BakedBean" scope="request" /> <H2>Bean level: <jsp:getProperty name="requestBean" property="level" /> t "l l" </H2> <H2>Dish bean goes with: <jsp:getProperty name="requestBean" property="goesWith" /> </H2> 41
  • 21. Request-Based Sharing: Result (Initial Request) 42 Request-Based Sharing: Result (Later Request) 43
  • 22. Sharing Beans Example 3: Session-Based Sharing • Create the bean – U j Use jsp:useBean with scope="session". B ih " i " • Modify the bean – Use jsp:setProperty with property="*". jp p y p p y – Then, supply request parameters that match the bean property names. • Access the bean in the initial request – Use jsp:getProperty in the request in which jsp:setProperty is invoked. • Access the bean later – Use jsp:getProperty in a request that does not include request parameters and thus does not invoke jsp:setProperty. If this request is from the same client (within the session timeout), the previously timeout) modified value is seen. If this request is from a different client (or after the session timeout), a newly created bean is seen. 44 Session-Based Sharing: Code … <BODY> <H1>Baked Bean Values: session-based Sharing</H1> <jsp:useBean id="sessionBean" class="coreservlets.BakedBean" class="coreservlets BakedBean" scope="session" /> <jsp:setProperty name="sessionBean" property="*" /> t "*" <H2>Bean level: <jsp:getProperty name="sessionBean" property="level" / /> </H2> <H2>Dish bean goes with: <jsp:getProperty name="sessionBean" property="goesWith" /> 45 </H2></BODY></HTML>
  • 23. Session-Based Sharing: Result (Initial Request) 46 Session-Based Sharing: Result (Later Request -- Same Client) 47
  • 24. Session-Based Sharing: Result (Later Request -- New Client) 48 Sharing Beans Example 4: Application-Based Sharing • Create the bean – U j Use jsp:useBean with scope="application". B ih " li i " • Modify the bean – Use jsp:setProperty with property="*". jp p y p p y – Then, supply request parameters that match the bean property names. • Access the bean in the initial request – Use jsp:getProperty in the request in which jsp:setProperty is invoked. • Access the bean later – Use jsp:getProperty in a request that does not include request parameters and thus does not invoke jsp:setProperty. Whether this request is from the same client or a different client (regardless of the session timeout), the previously modified value is seen. 49
  • 25. Application-Based Sharing: Code <BODY> <H1>Baked Bean Values: application-based Sharing</H1> <jsp:useBean id="applicationBean" class="coreservlets.BakedBean" class="coreservlets BakedBean" scope="application" /> <jsp:setProperty name="applicationBean" property="*" /> t "*" <H2>Bean level: <jsp:getProperty name="applicationBean" property="level" / /> </H2> <H2>Dish bean goes with: <jsp:getProperty name="applicationBean" property="goesWith"/> 50 </H2></BODY></HTML> Application-Based Sharing: Result (Initial Request) 51
  • 26. Application-Based Sharing: Result (Later Request -- Same Client) 52 Application-Based Sharing: Result (Later Request -- New Client) 53
  • 27. Conditional Bean Operations • Bean conditionally created – jsp:useBean results in new bean being instantiated only if no bean with same id and scope can be found. – If a bean with same id and scope is found, the preexisting found bean is simply bound to variable referenced by id. • Bean properties conditionally set p p y – <jsp:useBean ... /> replaced by <jsp:useBean ...>statements</jsp:useBean> >statements</jsp:useBean> – The statements (jsp:setProperty elements) are executed only if a new bean is created, not if an existing bean is found. 54 Conditional Bean Creation: AccessCountBean public class AccessCountBean { p private String firstPage; g g private int accessCount = 1; public String getFirstPage() { return(firstPage); } public void setFirstPage(String firstPage) { this.firstPage this firstPage = firstPage; } public int getAccessCount() { return(accessCount); t ( C t) } public void setAccessCountIncrement(int increment) { accessCount = accessCount + increment; } } 55
  • 28. Conditional Bean Creation: SharedCounts1.jsp SharedCounts1 jsp <jsp:useBean id="counter" class="coreservlets.AccessCountBean" scope="application"> <jsp:setProperty name="counter" property="firstPage" value SharedCounts1.jsp value="SharedCounts1.jsp" /> </jsp:useBean> Of SharedCounts1.jsp (this page), <A HREF="SharedCounts2.jsp">SharedCounts2.jsp</A>, and <A HREF="SharedCounts3 jsp">SharedCounts3 jsp</A> HREF="SharedCounts3.jsp">SharedCounts3.jsp</A>, <jsp:getProperty name="counter" property="firstPage" /> was the first page accessed. <P> Collectively, th th C ll ti l the three pages h have b been accessed d <jsp:getProperty name="counter" property="accessCount" /> times. <jsp:setProperty name="counter" property="accessCountIncrement" value="1" /> 56 Accessing SharedCounts1, SharedCounts2, SharedCounts2 SharedCounts3 • SharedCounts2.jsp was accessed first. • Pages have been accessed twelve previous times by an arbitrary number of clients 57
  • 29. Summary • Benefits of jsp:useBean – Hides the Java syntax – Makes it easier to associate request parameters with Java objects (bean properties) – Simplifies sharing objects among multiple requests or servlets/JSPs • j jsp:useBean B – Creates or accesses a bean • jsp:setProperty – Sets bean property (i.e. passes value to setXxx) • You usually use p p y y property="*" to p pass in request params q p • jsp:getProperty 58 – Puts bean property (i.e. getXxx call) into servlet output © 2010 Marty Hall Questions? Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. 59 Developed and taught by well-known author and developer. At public venues or onsite at your location.