Beginner’s Guide to Web Development – The Sample Application

To conclude this guide, we are going to use all that we've learned so far and create a sample application to better illustrate how web development is done in the real world. The name of this sample application is "Budget Calculator". The concept is that a user enters in their monthly expenses, such as rent, car payments, etc., and the budget calculator determines the sum of all of the user's expenses, as well as the percentages of the total expense made up by each individual category.

All of our work for the sample application will go in the sample_applcation directory under our current work directory. We have yet to create this directory, so please create it now:

c:\tomcat\webapps\examples\jsp\work\sample_application\

Also make sure Tomcat is up and running.

One of the first things we need to do is create our style classes that will define the look and feel of our application. Create a file named sample_applciation.css under the sample_applcation directory you just created. Copy or type the below into the "sample_application.css" file.

.bodyback {background: #FFFFF0}

.maintext {color: #000000;
font-family: Helvetica, Arial, sans-serif;
font-size: 10pt;
text-align: left;
font-weight: bold}

.selecttext {color: #000000;
font-family: Helvetica, Arial, sans-serif;
font-size: 10pt;
text-align: left;
font-weight: normal}

.displaytext {color: #000000;
font-family: Helvetica, Arial, sans-serif;
font-size: 10pt;
text-align: right;
font-weight: normal}

.toptext {color: #FFFFF0;
background: #000000;
font-family: Helvetica, Arial, sans-serif;
font-weight: bold;
font-size: 18pt;
text-align: center}

The "bodyback" class above will be used to set the background color for the pages of our sample application. The "maintext", "selecttext", and "displaytext" classes will be used to display variations on the text we use for directions and displaying information. The "toptext" class will be used for the name of our application, which we will place at the top of each page.

Notice the way we define the color style. We use a '#' sign, followed by a six digit number. The six digit number corresponds to the red, green, and blue content of the color. The first two numbers are red, the second two green, and the last two blue. The available values go from '00' to 'FF' with all numbers from '0' to '9' available and all letters from 'A' to 'F' available. For example, take a look at the following values and their respective colors:

#FF0000 = RED
#00FF00 = GREEN
#0000FF = BLUE

By changing the values of the six digit numbers, we can change the shade of the red, green, and blue colors that combine to form the final color. Here's an example:

#FF00FF = PURPLE
#33CCFF = LIGHT BLUE

There are many possible color cominations. The above are just a few. Take a look at HTML Tag Reference to see some more color examples, or the HTML Guide for more information. The rest of the style attributes should be self-explanatory. The font-family gives the type of font we're using. The font-weight gives the boldness of the font. The font-size gives the size of the font, and the text-align tells how the text will be aligned. For example, a text-align value of "right" will right-justify the text.

Now that we've created our style classes that we will use for each web page, it's time to create our first JSP page. The first step we need to take is to create the HTML for this page. Here is the code:

<html>

<head>

<link href="sample_application.css" rel="stylesheet" type="text/css">

<title>Sample Application</title>

</head>

<body class="bodyback">


<table width="100%">
<tr>
<td class="toptext" height="100">The Budget Calculator</td>
</tr>
</table>

<table width="100%">

<tr>
<td width="25%" height="50">&nbsp;</td>
<td width="50%">&nbsp;</td>
<td width="25%">&nbsp;</td>
</tr>

<tr>
<td width="25%""></td>
<td width="50%" class="maintext">
Hello, and welcome to the Budget Calculator. At this site, we help you determine a monthly budget by
calculating your monthly expenses. Please put dollar amounts in the form below so we can
determine how much money you spend each month.
</td>
<td width="25%">&nbsp;</td>
</tr>

<tr>
<td width="25%">&nbsp;</td>
<td width="50%" class="selecttext">
<br><br>
Please enter numbers only. No $ signs please. Ex. 135
<br>
<br>
<form name=expense action="expense.jsp" method="GET">
<input type="text" size="5" name="rent" value=""> Rent or Mortgage
<br><br>
<input type="text" size="5" name="car" value=""> Car Expense
<br><br>
<input type="text" size="5" name="utilities" value=""> Utilities (i.e. electric, gas, etc.)
<br><br>
<input type="text" size="5" name="food" value=""> Food Expense (i.e. groceries, restaurant bills, etc.)
<br><br>
<input type="text" size="5" name="entertainment" value=""> Entertainment
<br><br>
<input type="text" size="5" name="other" value=""> Other
<br><br>
<input type="submit" name="submit" value="submit">
</form>
</td>
<td width="25%">&nbsp;</td>
</tr>
</table>


</body>

</html>

We used two tables to create the web page. The first table is to hold the title of the application, "Budget Calculator". We used the class "toptext" to achieve the black background and the size and color of the text. We applied this style class to the <td> tag to accomplish this.

The second table is to hold the rest of the information relating to the application. By splitting the table into several rows, and dividing those rows into cells, we were able to align the text nicely on the page. The two style classes used for this table were "maintext" and "selecttext". Notice the use of the form to collect data from the user. This is one of the most common uses of HTML forms.

Also, notice the widths and heights we used on the tables and table cells. These were used to space the text appropriately. In the second table we had '3' cells (td) for each row (tr). Even though we didn't put text in each cell, we still need to account for the cell so our table displays correctly. To account for a cell that has no data, we use the &nbsp piece of code.

Even though this page has no JSP code on it, we will still save it as a JSP page and run it under our Tomcat server. Thus, save the above code as enter.jsp under the following directory:

c:\tomcat\webapps\examples\jsp\work\sample_application\

Test this page by going to the following URL:

http://localhost:8080/examples/jsp/work/sample_application/enter.jsp

We now have our style classes and the first page of our sample application written. Next, it's time to write the second page of our application. This page will accept the values entered by the user on the first page, enter.jsp, and ask the user if they are correct. If the values are correct, the page will submit the values to the next page in the application. This will be the first page of the application that has JSP code. This page will make use of methods, the request object, the session object, Java basics, and the programming basics topics contained in the Java and JSP sections of the tutorial. The page will also make use of all of our HTML and communication topics. Save the following code as expense.jsp in your sample_application directory:

<%!
boolean checkForNull (String s)
{
    if (s.equals(""))
    {
        return true;
    }
    return false;
}
%>

<%
String rent = request.getParameter ("rent");
String car = request.getParameter ("car");
String utilities = request.getParameter ("utilities");
String food = request.getParameter ("food");
String entertainment = request.getParameter ("entertainment");
String other = request.getParameter ("other");

if (checkForNull(rent))
{
    rent = "0";
}

if (checkForNull(car))
{
    car = "0";
}

if (checkForNull(utilities))
{
    utilities = "0";
}

if (checkForNull(food))
{
    food = "0";
}

if (checkForNull(entertainment))
{
    entertainment = "0";
}

if (checkForNull(other))
{
    other = "0";
}

session.setAttribute ("rent", rent);
session.setAttribute ("car", car);
session.setAttribute ("utilities", utilities);
session.setAttribute ("food", food);
session.setAttribute ("entertainment", entertainment);
session.setAttribute ("other", other);
%>

<html>

<head>
<link href="sample_application.css" rel="stylesheet" type="text/css">

    <title>Sample Application</title>

</head>

<body class="bodyback">


table width="100%" >
    <tr>
        <td class="toptext" height="100">The Budget Calculator</td>
    </tr>            
</table>

<table width="100%">
    
    <tr>
        <td width="25%" height="50">&nbsp;</td>
        <td width="50%">&nbsp;</td>
        <td width="25%">&nbsp;</td>
    </tr>

    <tr>
        <td width="25%""></td>
        <td width="50%" class="maintext">
            Listed below are the values you entered for each category of expense on the previous page.
            If the numbers are correct, please hit submit to proceed to the next page. If not, please
            click <a href="enter.jsp">here</a> to re-enter your data.
            
             </td>
        <td width="25%">&nbsp;</td>
    </tr>
    
    <tr>
        <td width="25%">&nbsp;</td>
        <td width="50%" class="selecttext">
            <br><br>
            Here are your values:
            <br><br>
            
            <table>
                <tr>
                    <td class="displaytext"><%=rent%></td>
                    <td width="20">&nbsp;</td>
                    <td class="selecttext">Rent or Mortage</td>
                </tr>
                
                <tr>
                    <td class="displaytext"><%=car%></td>
                    <td width="20">&nbsp;</td>
                    <td class="selecttext">Car</td>
                </tr>
                
                <tr>
                    <td class="displaytext"><%=utilities%></td>
                    <td width="20">&nbsp;</td>
                    <td class="selecttext">Utilities</td>
                </tr>
                
                <tr>
                    <td class="displaytext"><%=food%></td>
                    <td width="20">&nbsp;</td>
                    <td class="selecttext">Food</td>
                </tr>
                
                <tr>
                    <td class="displaytext"><%=entertainment%></td>
                    <td width="20">&nbsp;</td>
                    <td class="selecttext">Entertainment</td>
                </tr>
                
                <tr>
                    <td class="displaytext"><%=other%></td>
                    <td width="20">&nbsp;</td>
                    <td class="selecttext">Other</td>
                </tr>
            </table>
            
            <form name="expense" action="calculate.jsp" method="GET">
            <input type="submit" name="submit" value="submit">
            </form>
            </table>
             </td>
        <td width="25%">&nbsp;</td>
    </tr>
</table>


</body>

</html>

After you've saved the above code to the correct directory, you can test the pagee by going to the enter.jsp page you created earlier, entering some sample data, and hitting submit. You will be taken to the expense.jsp page. Let's now analyze the code.

The format we used for the HTML for this page was very similar to our first page, enter.jsp. One thing you may have noticed is the use of a nested table, which is a table inside another table. This is perfectly legal. In our case, we used a nested table so that we could format our data without affecting other data on the page. The data in this case were the three categories -- expense, percent, and category -- and their values. By surrounding these values with a table and putting the values in cells within the table, we guaranteed proper spacing between the three categories. Once again we used a form to pass our information to the next page, calculate.jsp, and used our styles to define the look of the page.

This page makes significant use of JSP code. Let's examine the page more closely. Take note of the following line:

String rent = request.getParameter ("rent");

Here we make use of the built-in request object of JSP to retrieve information passed from the previous page. We perform this operation for all of the code we want to retrieve. In this case, all of our expense categories.

Take a look at the following code:

if (checkForNull(rent))
{
    rent = "0";
}

Here we are calling a method we created, checkForNull. This method returns true if the value of the rent string is null. The method returns false if rent is not null. What we are doing here is some error checking to make sure we do not try to use a null value of rent. This prevents our page from throwing an error if rent was indeed null. A possible way that rent could be null would be if the user did not enter a value for rent on the previous page. We call this method for each of our expense categories. Let's take a look at the code for the method.

<%!
boolean checkForNull (String s)
{
    if (s.equals(""))
    {
        return true;
    }
    return false;
}
%>

Here we make use of the declaration tag, <%!, to define a method. Our method returns true or false so it is defined as a boolean. We pass a String value into the method. In our "if" statement, we check for the empty string, "", by calling the ".equals" method available to all objects. If the string passed into the method is equal to the empty string, the method returns true. If it isn't, the method returns false.

We also make use of the built-in session object in this page. Take a look at the following line of code:

session.setAttribute ("rent", rent);

Here, we are calling the setAttribute method of the session object. Remember, we need to pass in a name for the attribute we are setting, in this case this is "rent"; and we also need to pass in the attribute, which is the string rent. After this code is executed, the string rent is stored in our session and can be accessed by any JSP page as long as the session is still active.

There is one more piece of JSP code that we want to go over. Take a look at the following:

<%=rent%>

Here, we are making use of the JSP expression, <%=>, tag to print output to the screen. We do this to display the values of each of the expense categories that were entered on the previous page.

This concludes our explanation of our expense.jsp page. Now we are ready to move on to the final JSP page in our sample application, calculate.jsp. Below is the code behind this page:

<%!
double getPercent (double num, double total)
{
    double d = 0.0;
    d = num / total;
    d = d * 1000;
    d = Math.round(d);
    d = d / 10;
    return d;
}
%>

<%
double[] expenseArray = new double[6];

String rent = (String) session.getAttribute("rent");
Double rentDouble = new Double (rent);
expenseArray[0] = rentDouble.doubleValue();


String car = (String) session.getAttribute("car");
Double carDouble = new Double (car);
expenseArray[1] = carDouble.doubleValue();

String utilities = (String) session.getAttribute("utilities");
Double utilitiesDouble = new Double (utilities);
expenseArray[2] = utilitiesDouble.doubleValue();

String food = (String) session.getAttribute("food");
Double foodDouble = new Double (food);
expenseArray[3] = foodDouble.doubleValue();

String entertainment = (String) session.getAttribute("entertainment");
Double entertainmentDouble = new Double (entertainment);
expenseArray[4] = entertainmentDouble.doubleValue();


String other = (String) session.getAttribute("other");
Double otherDouble = new Double (other);
expenseArray[5] = otherDouble.doubleValue();

double totalExpense = 0.0;
for (int i = 0; i < expenseArray.length; i++)
{
    totalExpense = totalExpense + expenseArray[i];
}

double rentPercent = getPercent (expenseArray[0], totalExpense);
double carPercent = getPercent (expenseArray[1], totalExpense);
double utilitiesPercent = getPercent (expenseArray[2], totalExpense);
double foodPercent = getPercent (expenseArray[3], totalExpense);
double entertainmentPercent = getPercent (expenseArray[4], totalExpense);
double otherPercent = getPercent (expenseArray[5], totalExpense);
%>

<html>

<head>

<link href="sample_application.css" rel="stylesheet" type="text/css">
    
    <title>Sample Application</title>

</head>

<body class="bodyback">


    <table width="100%" cellpadding="0" cellspacing="0" border=0>
        <tr>
             <td class="toptext" height="100">The Budget Calculator</td>
         </tr>            
</table>

<table width="100%">
    
    <tr>
        <td width="25%" height="50">&nbsp;</td>
        <td width="50%">&nbsp;</td>
        <td width="25%">&nbsp;</td>
    </tr>

    <tr>
        <td width="25%""></td>
        <td width="50%" class="maintext">
            Listed below are the percentages associated with each of your expense categories, as well as your
            total expenses.
            
             </td>
        <td width="25%">&nbsp;</td>
    </tr>
    
    <tr>
        <td width="25%">&nbsp;</td>
        <td width="50%" class="selecttext">
        <br><br>
        <table>
                <tr>
                    <td class="maintext">Expense</td>
                    <td width="20">&nbsp;</td>
                    <td class="maintext">Percent</td>
                    <td width="20">&nbsp;</td>
                    <td class="maintext">Category</td>
                </tr>
        
                <tr>
                    <td class="displaytext"><%=rent%></td>
                    <td>&nbsp;</td>
                    <td class="displaytext"><%=rentPercent%></td>
                    <td>&nbsp;</td>
                    <td class="selecttext">Rent or Mortage</td>
                </tr>
                
                <tr>
                    <td class="displaytext"><%=car%></td>
                    <td>&nbsp;</td>
                    <td class="displaytext"><%=carPercent%></td>
                    <td>&nbsp;</td>
                    <td class="selecttext">Car</td>
                </tr>
                
                <tr>
                    <td class="displaytext"><%=utilities%></td>
                    <td>&nbsp;</td>
                    <td class="displaytext"><%=utilitiesPercent%></td>
                    <td>&nbsp;</td>
                    <td class="selecttext">Utilities</td>
                </tr>
                
                <tr>
                    <td class="displaytext"><%=food%></td>
                    <td>&nbsp;</td>
                    <td class="displaytext"><%=foodPercent%></td>
                    <td>&nbsp;</td>
                    <td class="selecttext">Food</td>
                </tr>
                
                <tr>
                    <td class="displaytext"><%=entertainment%></td>
                    <td>&nbsp;</td>
                    <td class="displaytext"><%=entertainmentPercent%></td>
                    <td>&nbsp;</td>
                    <td class="selecttext">Entertainment</td>
                </tr>
                
                <tr>
                    <td class="displaytext"><%=other%></td>
                    <td>&nbsp;</td>
                    <td class="displaytext"><%=otherPercent%></td>
                    <td>&nbsp;</td>
                    <td class="selecttext">Other</td>
                </tr>
                
                <tr>
                    <td class="displaytext" colspan="5"><hr></td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                 <td>&nbsp;</td>
                    <td class="selecttext">&nbsp;</td>
                </tr>
                
                <tr>
                    <td class="displaytext"><%=totalExpense%></td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td class="selecttext">Total Expense</td>
                </tr>
            </table>
             </td>
        <td width="25%">&nbsp;</td>
    </tr>
</table>


</body>

</html>

This is the final page of our sample application and the most complex as far as programming logic goes. This page retrieves the information stored in the session object and performs calculations on it. Let's analyze some of the code. Look at the following:

double[] expenseArray = new double[6];

Here we make use of the Java array. In this case, we declare an array of type double and give it a size of '6'. This means we can fill up to '6' cells of this array. This array is used to hold the values for each of the expense categories. Take a look at the following line of code:

String rent = (String) session.getAttribute("rent");

Here we make use of the getAttribute method of the session object. We use this method to retrieve the value of the rent expense category that we stored in the session on the previous page. Notice the use of the casting, which we talked about in a previous section. Since rent is a string, we need to cast it to a string. We call getAttribute to get all of our expense category values from the session. Take a look at the following code:

Double rentDouble = new Double (rent);
expenseArray[0] = rentDouble.doubleValue();

The above code takes our string "rent", converts it to the double wrapper Double, then stores the "double" value obtained from this wrapper in the expenseArray array. Since rent is stored as a string value, we cannot perform arithmetic operations on it. Becuase of this, we needed to perform the above code to convert the string value to a double value. The wrappers used in the code were covered in the "Java Basics" section.

After the final conversion of an expense category from "String" to "double", which occurs with the "other" category, we have the following: an array, expenseArray, holding a double value representing each of the expense categories. The next calculation we want to perform is to add up all of the expenses to arrive at a total expense. This can be done using a for loop. Take a look at the following:

double totalExpense = 0.0;
for (int i = 0; i < expenseArray.length; i++)
{
    totalExpense = totalExpense + expenseArray[i];
}

First, we define a double data type, totalExpense, to hold the number in which we arrive for our total expense. Then, we create a for loop to loop through each cell of the expenseArray array and calculate the sum of the values contained in this array. Thus, after the for loop has finished, we have a variable, totalExpense, that contains the sum of all expenses. The final logic we need to perform is to get the percents for each expense cateogory based on the total expense. To help us do this, we create the following method:

double getPercent (double num, double total)
{
    double d = 0.0;
    d = num / total;
    d = d * 1000;
    d = Math.round(d);
    d = d / 10;
    return d;
}

This method takes two values, one represents the expense of the individual category, the other represents the total expenses. To get the percentage expense of the category, the category expense needs to be divided by the total expense, and then multiplied by 100 to be in percent format. However, we only want to show the percent to two decimal places, so we need to use some rounding tricks to get this accomplished. So, we take our category expense divided by the total expense and arrive at a decimal value. We then take that value times 1000. Calling Math.round on this value and dividing by 10 gives us a number with a maximum of two values to the right of the decimal point. This is the number we want, and as such, this is the number we return. Thus, by calling getPercent on each of our expense categories, we get the percentage expense for them. Now all we need to do is print out this information to the page. We use the JSP expression to do this. The following is an example:

<%=rentPercent%>

The HTML used to create this page is very similar to the HTML used to create the previous page. Once again, we use nested tables for proper formatting, and use JSP expressions to print out our dynamic data.

We've now covered all of the code for our sample application. Hopefully you had a chance to test the code on your own machine and see it in action. Be sure to take the code from the sample application and experiment with the values. This should help you gain a better understanding of exactly what each piece of code is going.

This brings us to the end of the guide. It's been a long road to get this far. We've covered everything from HTML basics to complex programming logic. If you've gotten to the point where you can understand the topics covered and the sample application, you should be well on your way to becoming a successful web developer. Good luck to you and happy developing from Richardson Publications (www.richardsonpublications.com).