Handout 37
Web Design & Development                                                         CS-506
  Lecture 37
                       JSP Action Elements and Scope
  The journey we had started of JSP is very much covered except of JSP action elements.
  In this handout, we’ll study the use of JSP action elements. Further also learn how and
  where to store JavaBean objects that can be shared among JSP pages.
  Let’s first quickly look on the JSP journey to find out where we have reached.
     Directive Elements
      –     Provides global control of JSP ……..……………..               <%@           %>
     Scripting Elements
      –     JSP comments ……………………………………...                           <%--          --%>
      –     declarations ……………………………………...                           <%!           %>
               • Used to declare instance variables & methods
      –  expressions ……………………………………...                               <%=           %>
implicit    • A java code fragment which returns String
objects
      – scriptlets   ……………………………………...                               <%            %>
            • Blocks of java code
     Action Elements
      –     Special JSP tags ……..……………………………..                       <jsp: .….     />
  JSP Action Elements
  JSP action elements allow us to work with JavaBeans, to include pages at request time
  and to forward requests to other resources etc.
  Format
  Expressed using XML syntax
            -   Opening tag     <jsp:actionElement attribute=”value” ….. >
            - Body               body
            - Closing tag       </jsp:actionElement>
  Empty tags (without body) can also be used like
            <jsp:actionElement attribute=”value” ….. >
  - 460 -
Handout 37
Web Design & Development                                                              CS-506
Some JSP Action Elements
   To work with JavaBeans
       - <jsp:useBean />
         - <jsp:setProperty />
         - <jsp:getProperty />
   To include resources at request time
        - <jsp:include />
   To forward request to another JSP or Servlet
       - <jsp:forward />
   To work with applets
       - <jsp:plugin />
Working with JavaBeans using JSP Action Elements
The three action elements are used to work with JavaBeans. These are discussed in detail
below.
JSP useBean Action Element
It is used to obtain a reference to an existing JavaBean object by specifying id(name of
object) and scope in which bean is stored. If a reference is not found, the bean is
instantiated.
The format of this action element is:
<jsp:useBean           id = “name”
                       scope = “page|request|session|application”
                       class=“package.Class ” />
The id attribute specifies the name of the JavaBean object that is also used for later
references. The scope attribute can have one possible value out of page, request,
session and application. If this attribute is omitted, the default value of scope attribute is
page. We’ll discuss in detail about scope shortly.
The class attribute specifies the type of object is going to be created.
jsp:useBean is being equivalent to building an object in scriptlet. For example to
build an object of MyBean using scriptlet is:
         <%
               MyBean m = new MyBean( );
         %>
- 461-
Handout 37
Web Design & Development                                                         CS-506
Achieving above functionality using jsp:useBean action element will look like
this:
          <jsp:useBean        id = “m”
                              scope = “page”
                              class=“vu.MyBean”          />
In the above code snippet, we are assuming that MyBean lies in vu package.
JSP setProperty Action Element
To set or change the property value of the specified bean. String values are converted to
types of properties by using the related conversion methods.
The format of this action element is:
<jsp:setProperty              name = “beanName or id”
                              property = “name”
                              value =“value” />
The name attribute should match the id given in jsp:useBean. The property
attribute specifies the name of the property to change and the value attribute specifies
the new value.
jsp:setProperty is being equivalent to following code of scriptlet. For example to
change the name property of m (instance of MyBean) using scriptlet is:
          <%
               m.setProperty(“ali”);
          %>
Achieving above functionality using jsp:setProperty action element will look like
this:
          <jsp:setProperty              name = “m”
                                        property = “name”
                                        value = “ali” />
- 462 -
Handout 37
Web Design & Development                                                              CS-506
JSP getProperty Action Element
Use to retrieves the value of property, converts it to String and writes it to output stream.
The format of this action element is:
<jsp:getProperty               name = “beanName or id”
                               property = “name” />
jsp:getProperty is being equivalent to following code of scriptlet. For example to
retrieve the name property of m (instance of MyBean) followed by writing it to output
stream, scriptlet code will look like:
         <%
               String name = m.getName( );
               out.println(name);
         %>
Achieving above functionality using jsp:getProperty action element will look like
this:
         <jsp:getProperty               name = “m”
                                        property = “name” />
-463 -
Handout 37
Web Design & Development                                                        CS-506
Example Code: Calculating sum of two numbers by using action
elements and JavaBean
This example contains index.jsp and result.jsp and one JavaBean i.e.
SumBean. User will enter two numbers on index.jsp and their sum will be
displayed on result.jsp. Let’s examine these one after another
SumBean.java
The SumBean has following attributes
    –     firstNumber
    –     secondNumber
    –     sum
The firstNumber and secondNumbers are “write-only” properties means for these only
setters would be defined. Whereas sum is a “read-only” property as only getter would be
defined for it.
The SumBean also contain one additional method for calculating sum i.e.
calulateSum(). After performing addition of firstNumber with secondNumber, this
method will assign the result to sum attribute.
 package vu;
 import java.io.*;
 public class SumBean implements Serializable{
         private int firstNumber;
         private int secondNumber;
         private int sum;
         // no argument constructor
         public SumBean() {
             firstNumber = 0;
             secondNumber = 0;
             sum = 0;
         }
         // firstNumber & secondNumber are writeonly properties
         // setters
         public void setFirstNumber(int n){
             firstNumber = n;
         }
         public void setSecondNumber(int n){
             secondNumber = n;
         }
- 464-
Handout 37
Web Design & Development                                                         CS-506
         // no setter for sum
         // sum is a read only property
         public int getSum( ){
             return sum;
         }
         // method to calculate sum
         public void calculateSum() {
             sum = firstNumber + secondNumber;
         }
 }
index.jsp
This page will display two text fields to enter number into them.
 <html>
     <body>
             <h2>Enter two numbers to calculate their sum</h2>
             <form name="myForm" action="result.jsp">
                 <h3>
                 Enter first numebr
                 <input type="text" name="num1" />
                 <br/>
                 Enter second numebr
                 <input type="text" name="num2" />
                 <br/>
                 <input type="submit" value="Calculate Sum" />
                 </h3>
             </form>
     </body>
 </html>
result.jsp
This page will calculate the sum of two entered numbers by the user and displays the sum
back to user. The addition is performed using SumBean
 <%-- importing vu package that contains the SumBean --%>
 <%@page import="vu.*"%>
 <html>
   <body>
     <h2>The sum is:
          <%-- instantiating bean using action element -- %>
- 465-
Handout 37
Web Design & Development                                             CS-506
         <%--
             //Servlet equivalent code of useBean
              SumBean sBean = new SumBean();
         --%>
         <jsp:useBean id="sBean" class="vu.SumBean" scope="page"/>
         <%-- setting firstNumber property of sBean
               using action elements
          -- %>
         <%-- implicit conversion from string to int as num1 is of type
              String and firstNumber is of type int
          --%>
         <%--
                //Servlet equivalent code of setProperty for num1
                int no = Integer.parseInt(request.getParameter("num1"));
                sBean.setFirstNumber(no);
         --%>
         <jsp:setProperty name="sBean"
                          property="firstNumber" param="num1" />
         <%--
                //Servlet equivalent code of setProperty for num2
                int no = Integer.parseInt(request.getParameter("num2"));
                sBean.setSecondNumber(no);
         --%>
         <jsp:setProperty name="sBean"
                          property="secondNumber" param="num2" />
         <%
           // calling calculateSum() method that will set the value of
           // sum attribute
           sBean.calculateSum();
         %>
         <%--
                // servlet equivalent code of displaying sum
                int res = sBean.getSum();
                out.println(res);
         --%>
         <jsp:getProperty name="sBean" property="sum" />
       </h2>
     </body>
 </html>
- 466-
Handout 37
Web Design & Development                                                                CS-506
Sharing Beans & Object Scopes
So far, we have learned the following techniques to create objects.
          -    Implicitly through JSP directives
          -    Explicitly through actions
          -    Directly using scripting code
Although the beans are indeed bound to local variables, that is not the only behavior.
They are also stored in four different locations, depending on the value of the optional
scope attribute of jsp:useBean. The scope attribute has the following possible
values: page, request, session and application.
Let’s discover what impact these scopes can produce on JavaBeans objects which are
stored in one of these scopes.
   page
    This is the default value of scope attribute, if omitted. It indicates, in addition to being
    bound to local variable, the bean object should be placed in the pageContext
    object. The bean’s values are only available and persist on JSP in which bean is
    created.
    In practice, beans created with page scope are always accessed (their values) by
    jsp:getProperty, jsp:setProperty, scriptlets or expressions later in the
    same page. This will be more cleared with the help of following diagram:
              first.jsp                             second                            third.jsp
                             (1) request 1            .jsp        (3) request 1
                                                                  or request 2
                                          (2) create                       (4) Values not
                                                                           available
      MyBean m = new MyBean();                      MyBean m
      m.setName(“ali”);                            [name = ali]
                                               PageContext
- 467 -
Handout 37
Web Design & Development                                                                         CS-506
    In the diagram above, first.jsp generates a request “request 1” that is submitted
    to second.jsp. Now, second.jsp creates an object m of MyBean by calling its
    default constructor and stores a value “ali” for the name property by making a call to
    appropriate setter method. Since, the scope specified in this example is “page”
    when the object of MyBean is instantiated using jsp:useBean action element.
    Therefore, object (m) of MyBean is stored in PageContext.
    Whether, second.jsp forwards the same request (request 1) to third.jsp or
    generates a new request (request 2), at third.jsp, values (e.g. ali) stored in
    MyBean object m, are not available. Hence, specifying scope “page” results in using
    the object on the same page where they are created.
   request
    This value signifies that, in addition to being bound to local variable, the bean object
    should be placed in ServletRequest object for the duration of the current
    request. In other words, until you continue to forward the request to another
    JSP/servlet, the beans values are available. This has been illustrated in the following
    diagram.
         first.jsp                    second                        third.jsp                    fourth.jsp
                     (1) request 1      .jsp        (3) request 1                (5) request 2
                               (2) create             (4) values available      (6) values not available
                                     MyBean m
                                     [name = ali]
                                 ServletRequest
    In the diagram above, MyBean is instantiated by specifying scope = “request”
    that results in storing object in ServletRequest. A value “ali” is also stored in m
    using setter method.
    second.jsp forwards the same request (request 1) to third.jsp, since scope of
    m (object of MyBean) is request, as a result third.jsp can access the
    values(e.g. ali) stored in m. According to the figure, third.jsp generates a new
    request (request 2) and submits it to fourth.jsp. Since a new request is generated
    therefore values stored in object m (e.g. ali) are not available to fourth.jsp.
- 468-
Handout 37
Web Design & Development                                                                             CS-506
     session
      This value means that, in addition to being bound to local variable, the bean object
      will be stored in the HttpSession object associated with the current request. As
      you already know, object’s value stored in HttpSession persists for whole user’s
      session. The figure below helps in understanding this concept.
    first.jsp                    second                            third.jsp                      fourth.jsp
                (1) request 1      .jsp        (4) request 1                      (6) request 2
                           (3) create
                                                   (5)   values available   (7)   values available
                                MyBean m
                                [name = ali]
                                HttpSession
      In the diagram above, MyBean is instantiated by specifying scope = “session”
      that results in storing object in HttpSession. A value “ali” is also stored in m
      using setter method.
      Irrespective of request forwarding or new request generation from second.jsp to
      other resources, the values stored in HttpSession remains available until user’s
      session is ended.
     application
      This very useful value means that, in addition to being bound to local variable, the
      bean object will be stored in ServletContext. The bean objects stored in
      ServletContext is shared by all JSPs/servlets in the same web application. The
      diagram given below illustrates this scenario:
- 469-
Handout 37
Web Design & Development                                                                            CS-506
  first.jsp                     second                            third.jsp                      fourth.jsp
              (1) request 1       .jsp        (4) request 1                      (6) request 2
                         (3) create
                                                  (5)   values available   (7)   values available
                               MyBean m
                               [name = ali]
                          ServletContext
Summary of Object’s Scopes
   Most visible                                    Within all pages belonging to same
                              application          application
                                                   Only from pages belonging to same session
                                session            as the one in which they were created
                                                   Only within pages processing the request
                               request
                                                   in which they are created
                                 page              Objects may be accessed only within pages
   Least visible
                                                   where they are created
- 470 -
Handout 37
Web Design & Development                                                            CS-506
Let’s take another view of session, request & page scopes in the next figure that helps us
to understand the under beneath things.
The figure shows four JavaServer Pages. Each page has its own page scope. Therefore
objects stored in page scope are only available to same pages on which they are created.
Suppose page1 forwards the request to page2. Objects stored in request scope remains
available to page1 as well to page 2. Similar case is true for page 3 & page 4.
If user makes a visit to all these pages in one session, object’s values stored in session
scope remains available on all these pages.
- 471 -
Handout 37
Web Design & Development                                                            CS-506
To understand the difference between sessions & application scope, consider the
following figure:
As you can conclude from the figure, for each user (client), objects are stored in different
sessions. However, in the case of application scope, all users stores objects in single
place.
- 472-
Handout 37
Web Design & Development                                                            CS-506
More JSP Action Elements
Let’s talk about two important action elements. These are include & forward.
JSP include action Element
It is used to include files at request time. For example, to reuse HTML, JSP or plain text
content. It’s important to note that JSP content cannot affect main page (in which output
is included); only output of included JSP is used. It also allows updating of the included
content without changing the main JSP.
The jsp:include action element requires two attributes: page & flush.
          -   page: a relative URL of the file to be included.
          -   flush: must have the value “true”
          <jsp:include page = “relative URL”                     flush = “true”        />
jsp:include is being equivalent to following code of scriptlet. For example to
include the output of one.jsp , scriptlet code will look like:
     <%
          RequestDispatcher rd = request.getRequestDispatcher(“one.jsp”);
          rd.include(request, response);
     %>
Achieving above functionality using jsp:include action element will look like this:
          <jsp:include page = “one.jsp”                flush = “true”          />
JSP forward action Element
It is used to forward request to another resource. The format of jsp:forward action
is:
         <jsp:forward page = “one.jsp” />
jsp:forward is being equivalent to following code of scriptlet. For example to
forward the request to one.jsp , scriptlet code will look like:
     <%
          RequestDispatcher rd = request.getRequestDispatcher(“one.jsp”);
          rd.forward(request, response);
     %>
                                -------------------
- 473 -
Handout 37
Web Design & Development                               CS-506
References:
   Java A Lab Course by Umair Javed.
   Core Servlets and JavaServer Pages by Marty Hall
- 474-