Home arrow Java arrow Page 5 - Making Decisions, Decisions
JAVA

Making Decisions, Decisions


Most JavaServer Pages will need to perform one of several actions according to some condition. This is managed in the code through control statements, which come in three flavors: conditional, iterative, and branching. This article will explain the syntax Java provides for these statements, how and when to use arrays, and more. It is taken from chapter five of Beginning JSP 2 From Novice to Professional, written by Peter den Haan et. al. (Apress, 2004; ISBN: 1590593391).

Author Info:
By: Apress Publishing
Rating: 4 stars4 stars4 stars4 stars4 stars / 11
May 05, 2005
TABLE OF CONTENTS:
  1. · Making Decisions, Decisions
  2. · Creating Multidimensional Arrays
  3. · Comparing Data Values
  4. · Making Decisions
  5. · Understanding Variable Scope in Statement Blocks
  6. · How It Works
  7. · Understanding the Conditional Operator
  8. · Trying It Out: Working with the choose...when...when Construct
  9. · Understanding Loops and Iteration
  10. · Introducing Branching Statements
  11. · Trying It Out: Using Arrays

print this article
SEARCH DEVARTICLES

Making Decisions, Decisions - Understanding Variable Scope in Statement Blocks
(Page 5 of 11 )

Before moving any further, it’s time to throw in a cautionary note about variable scope and statement blocks. A statement block is a number of statements grouped together by being enclosed within two curly braces,{}. Look at the following code snippet:

int myVar1 = 100;
System.out.println(myVar1);
if (myVar1 > 0)
{
  int myVar2 = myVar1 * 2;
 
System.out.println(myVar1);
  System.out.println(myVar2);
}
System.out.println(myVar2);

In this code, you create two integer variables called myVar1 and myVar2, set them to 100 and 200, respectively, and attempt to print them twice. Therefore, you might expect the execution of this code to result in the following:

100
100
200
200

Actually, attempting to print myVar2 for the second time, once you’re outside the statement block following the if statement, will result in a compiler error. This is because myVar2 is declared inside the if statement block, so its scope is local to that block. Outside of the block, the variable doesn’t actually exist, so an error is thrown. For this code to compile and run, you’d need to move the declaration of myVar2 outside of the if block or alternatively remove the last System.out line.

You should note, however, that variables declared outside of the statement block may be used within the statement block as well, and you’re able to access myVar1 inside and outside of the if block.

You’ll now put into practice what you’ve learned about conditional statements. Because of the way tag libraries work and variable scope, you can’t simply add a tag after a JSTL <if> to provide else functionality; you have to turn to a different construct: the JSTL <choose>...<when> form.

Trying It Out: Working with the JSTL choose...when Construct

You’ll create a simple shopping cart where users enter the number of items they want to buy and then submit their order:

  1. First, create a new folder under webapps to hold the pages you’ll create in this chapter. Call the new directory Decisions. Then create a folder called WEB-INF within it, and then copy the JSTL lib folder inside that.

  2. Then create a file called whenexample.html in your new directory. This file starts with the standard HTML opening tags:

    <html>
       <head>
         <title>Chapter 5 Examples</title>
         <style type="text/css">
           .white {
            color: white;
           }
           .heading {
             background-color: #C0C0C0;
           }
        </style>
    </head>
    <body>

  3. Now you start an HTML form. This is a neat way of getting data from users. When the user clicks the submit button (which you’ll come to in a minute), all the data entered on the form can be sent off to a server for processing or sent to another page where it can affect the content of that page. You’ll use the latter of these two options, and as the action attribute indicates, the second page is called whenexamplehandler.jsp:

    <form method="POST" action="whenexamplehandler.jsp">
  4. The form itself will be laid out as an HTML table with three columns:

    <table border="0" cellpadding="0" cellspacing="0" width="439">
      <tr>
        <td width="157"><b>Shopping Cart</b></td>
        <td width="128"></td>
        <td width="148"></td>
      </tr>
      <tr class="heading">
        <td class="white" width="157">
          Product
        </td>
        <td class="white" width="128">
          ListPrice
        </td>
        <td class="white" width="148">
          Quantity
        </td>
      </tr>

  5. Each row of the table represents a single item available for purchase: 

    <tr>
      <td width="157">Beginning JSP</td>
      <td width="128">$49.99</td>
  6. The last column is a textbox where users can enter the quantity they want to order:

      <td width="148">
        <input type="text" name="quantity" size="4" />
      </td>
    </tr>

  7. Then you close the table and set up the submit button for when the user has entered all the necessary details. This button uses the POST method to pass the form values to the destination given by the <form> ’s action attribute:

      </table>
    <p>
      <input type="submit" value="Place Order" name="PlaceOrderBtn"/>
    </p>
  8. Now you close the other HTML tags, and you’re done with the HTML file:

        </form>
       </body>
    </html>

  9. When the user submits the form, the form data entered—which here is just the data in the quantity field—is submitted to the whenexamplehandler.jsp page. Create a file with this name now, again in the Decisions folder. This is quite a short file, and we’ll explain it in detail in the “How It Works” section. Here it is in full:

    <%@ taglib prefix="c" uri="http:// java. sun.com/jstl/core_rt" %>
    <%@ page info="If Example JSP"%>
    <html>
      <head>
        <title>Conditional Statements</title>
      </head>
      <body>
        <b>WHEN Statement Example ( Response ) <br /></b>
        <br />
        <c:choose>
          <c:when test="${param.quantity > 0}" >
            Thank you for your order!!
          </c:when>
          <c:otherwise>
            Sorry, please enter a positive quantity
          </c:otherwise>
        </c:choose>
      </body>
    </html>

  10. Start up Tomcat, and browse to the following URL in your browser: http://localhost:8080/Decisions/whenexample. html. Enter a positive number in the Quantity field, as shown in Figure 5-3. 


    Figure 5-3.  A form for testing the choose...when loop

  11. Click Place Order, and you should see output as in Figure 5-4.

    Figure 5-4.  The choose...when loop responds to your input.

  12. Click your browser’s Back button, and try it again, but this time enter 0 in the Quantity field and click Place Order. You should see the message asking you to supply a positive quantity.


blog comments powered by Disqus
JAVA ARTICLES

- Java Too Insecure, Says Microsoft Researcher
- Google Beats Oracle in Java Ruling
- Deploying Multiple Java Applets as One
- Deploying Java Applets
- Understanding Deployment Frameworks
- Database Programming in Java Using JDBC
- Extension Interfaces and SAX
- Entities, Handlers and SAX
- Advanced SAX
- Conversions and Java Print Streams
- Formatters and Java Print Streams
- Java Print Streams
- Wildcards, Arrays, and Generics in Java
- Wildcards and Generic Methods in Java
- Finishing the Project: Java Web Development ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials