Home arrow Java arrow Page 11 - 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 - Trying It Out: Using Arrays
(Page 11 of 11 )

To use an array, follow these steps:

  1. This example consists of a single JSP page that allows you to make changes to the book table you worked with in Chapter 3. The first thing you need to do then is copy the MySQL Connector/j JAR to the Decisions folderís lib folder (inside WEB-INF).

  2. Now you can start writing your JSP page, called arrayexample.jsp. You need to include the JSTL and SQL tag libraries: 

    <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
    <%@ taglib prefix="sql" uri="http://java.sun.com/jstl/sql_rt" %>
  3. Next, you need to provide the connection information for your database:

    <sql:setDataSource var="datasource" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/publish" user="publishuser" password="secret" />
  4. The next section of code is used to update the database when changes have been made. Donít worry about why that appears here just now; weíll explain that once the page is done:

    <c:if test="${!empty param.title}">
      <c:forEach items="${paramValues.title}" varStatus="i">
        <sql:update dataSource="${datasource}">
           UPDATE book
              SET title = ?,
                 price = ?
           WHERE id = ?
          <sql:param value="${paramValues.title[i.count-1]}" />
          <sql:param value="${paramValues.price[i.count-1]}" />
          <sql:param value="${paramValues.id[i.count-1]}" />
        </sql:update>
      </c:forEach>
    </c:if>

  5.  Now you run a query on the books table, extracting the id,title, and price fields:

    <sql:query var="books" dataSource="${datasource}">
    SELECT id, title, price FROM book
    </sql:query>

  6. The last thing to create is an HTML form for displaying information from the database:

    <html>
      <body>
        <form method="post">
          <table border="1">
            <tr>
              <th>id</td><th>title</td><th>price</td>
          </tr>

  7. You use another JSTL <forEach> to loop through all books that are to be displayed:

    <c:forEach var="row" items="${books.rows}">
      <input type="hidden" name="id" value="${row.id}" />
      <tr>
        <td>
          <input type="text" name="title" value="${row.title}" size="30" />
        </td>
        <td>
          <input type="text" name="price" value="${row.price}" size="6" />
        </td>
      </tr>
    </c:forEach>
  8. The last row in this table will contain the formís submit button. Because the form doesnít specify an action attribute, this button will post the form information back to this page itself

        <tr>
          <td colspan="3" align="center">
              <input type="submit" value="Save Changes" />
          </td>
         </tr>
        </table>
       </form>
      </body>
    </html>
  9. Open your browser, and go to http://localhost:8080/Decisions/arrayexample.jsp. You should see a page that looks something like Figure 5-9.


    Figure 5-9.  Books to change

  10. Change some values, and click the Save Changes button. You should get a response that looks like Figure 5-10 (depending on the items you chose):


    Figure 5-10. An updated book entry

How It Works

In step 4, you added some code inside the following JSTL <if> tag:

<c:if test="${!empty param.title}">

This tag uses the EL empty operator to see if thereís a title parameter for the page thatís neither null nor empty. When the page is first accessed from your browser, there wonít be any parameters at all, so the <if> block is skipped, and you load up the data from your database and come to the form that will display it on the page. The form has a hidden form field for the row ID of each book:

<input type="hidden" name="id" value="${row.id}" />

By storing this as a hidden form field, it will be returned to the server when the user submits the form, and thus the server could use it to determine which rows need updating in the database. You could place the ID in a textbox, but then users could edit the value, so you hide it.

Why do you hide the row ID, you may ask? As youíll recall from earlier examples of HTML forms, all values submitted to the server must be contained in one manner of form element or another.

You then create textboxes in the next two rows: one for the title and one for the price:

<input type="text" name="title" value="${row.title}" size="30" />
<input type="text" name="price" value="${row.price}" size="6" />

When the form is submitted, it posts back to the page itself. In other words, the page is regenerated but this time with the data you submitted available as parameters in the param array. So, now when you get to the first JSTL <if> tag, the test attribute, "${!empty param.title}", will evaluate to true, and you can use the <forEach> tag to iterate over the String array returned by $paramValues.title.

Remember that when you looked at <forEach> earlier, it has begin and end attributes and an attribute called var that denotes the current item in the loop. In this case, because the variable given in the var attribute holds the current value from the loop, which in this case would be the current title, you canít use it as the array index (that must be numerical!). Instead, you take advantage of the fact that the <forEach> tag uses its own status mechanism: varStatus. But     varStatus tracks the current iteration starting at one, and as arrays begin their index at zero, you have to do some math:

<sql:param value="${paramValues.title[i.count-1]}" />

You run through all the parameter values and update the database as necessary using the SQL UPDATE statement. Once the database update is complete, you continue down the page, extract the updated data from the database, and display it in a form just as before.


Why Not Try?

Try these exercises to improve your skills:

  • Extend the first example (whenexample.jsp) to add a set of conditional statements that grant a 10 percent discount for the first 14 days of each month and an additional 5 percent if the number of items ordered is greater than three. Grant a 25 percent total discount if the total items is greater than ten, regardless of the day of the month. For this example, just add a field for the user to enter the current day of the month, so you can read it as $param.dayOfMonth. Of course, a real system would get this information from the server, but you donít need to worry about that here.

  • Change the second example (whenexamplehandler2.jsp) so that it displays each book name up to and including the one selected. Put another way, if the user selects book 2, print the information for book 1 and book 2.

  • Use the JSTL <forEach> and <when> tags on a JSP page to count from one to 100 by ones, printing every third number (three, six, nine...). Now rewrite it so that it counts by threes. Use the var and varStatus attributes to verify your output.

  • Create an array of first names in ďrandomĒ order. Use any one of the looping techniques to print the names. Then use Arrays.sort() to order the names alphabetically, and print them again.


Summary

This chapter covered the basics of specifying decisions in your code and how you can use these decisions to affect program flow using control statements. There are three key types of control statements:

  • Conditional statements (if,if...else, and switch): Execution of a block of code is controlled by the result of evaluating an expression.

  • Iterative statements (for,while,do...while): Repeat the same code block a certain number of times.

  • Branching statements (break,continue,return): Used to exit a loop, the current loop iteration, or a method, respectively.

The chapter also covered arrays, which are groups of the same data type. They simplify the maintenance and processing of a large amount of variables. The for loop (or <forEach> tag in a JSP page) is a great tool for processing all the elements of an array in sequence. You looked at two-dimensional arrays and jagged arrays, which are invaluable in many situations. The chapter closed by looking at the sort method of the java.util package.

The main reason for using arrays and control statements is that they make code simpler, easier to maintain, and more reusable. The next chapter introduces tag libraries, which can simplify JSP scripts still further.


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

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