There are two objectives to this workshop: first is to format a number for display and the second objective is to convert a String to double so that some basic maths can be carried out.
This workshop should take no longer than 60 minutes.
The following demonstrates the objective of this workshop.
<html> <head> <title>Directives</title> </head> <body> <% //Declare number and string double dblSalary = 5000; String strRent = "400"; %> <p> Number formatted as string: <b><%= makeString(dblSalary) %></b> </p> <% //Increase rent by 10% double dblNewRent = makeDouble(strRent); dblNewRent = dblNewRent + (dblNewRent * 0.1); %> <p> String converted to number and back again: <b><%= makeString(dblNewRent) %></b> </p> </BODY> </HTML>
makeString() and
makeDouble(). Add a declaration section to your JSP and that includes the declaration
of these two methods:
<%!
//Method for formatting a double as a string
private String makeString(double n)
{
}
//Method for formatting a string to a double
private double makeDouble(String s)
{
}
%>
makeString() that will convert a double to a String. Java
has some clever methods that offer great flexibility and the following code is one such example,
NumberFormat nf = NumberFormat.getCurrencyInstance
(Locale.UK);
return nf.format(n);
NumberFormat class is defined in the package java.text and
the Locale class is defined in the package java.util. Add a directive
that references both these classes.makeDouble() that will convert a double to a String:Double d = new Double(s); return d.doubleValue();
Double class is defined in the package java.lang and this
package must also be referenced in a directive.makeString() method
to another region, Locale.US for example, and access the JSP again to see the difference.
By now your code should look like this:
Now these methods for formatting numbers as currenices and converting trings to doubles are pretty useful and it is likely that we'll want to use them again in other JSPs. This is an ideal scenario for exploiting the include directive.
By now your code should look like this:
It is a good practice to work with include files in this way. First build the JSP as a single file and then cut and paste the text into the file that is being included.
An common error that can be made with include files is placing the Java code in the include file
but forgetting the <%...%> tags. Other errors include declaring a variable both in
the include file and in the parent JSP.
A good method for debugging is to copy and paste the code from the include file to the parent JSP at the exact point of the include directive and then look for problems such as above.
Now that you are an expert in JSP Syntax go for top marks in the following quiz.