Making Decisions, Decisions - Trying It Out: Using Arrays
(Page 11 of 11 )
To use an array, follow these steps:
- 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).
- 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" %>
- 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" />
- 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>
- 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>
- 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>
- 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>
- 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>

Figure 5-9. Books to change
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. |
|
This article was excerpted from Beginning JSP 2: From Novice to Professional by Peter den Haan et. al. (Apress, 2004; ISBN: 1590593391). Check it out at your favorite bookstore. Buy this book now.
|
|