HTML Forms and JSP
Retrieving HTML form parameters
- JSP files can be invoked in response to an HTML Post or Get event
from an
HTML form. This form might reside in the JSP itself or be a
totally
separate file.
<FORM action = "url of the jsp"
Method = "get" or "post" name = "formname">
- if you use the "Get" method, then data from the form is encoded
into the url that is passed to the JSP file.
- if you use the Post method, the url is not changed, instead the
data is passed internally in the request to the jsp.
- In both cases the jsp file can access the form data using the
same getParameter method.
- using the Get method allows the user to "bookmark" the request
and get the same results a second time (without having to fill in the
form)
- This allows your JSP to provide different output each time it is
invoked.
- Each form element has a name associated with it. Your JSP
can
get the value for elements by using the built in JSP request object.
- e.g. String customerName =
request.getParameter("name");
- request.getParameter()
returns
a string, you can convert this to a double using Double.parseDouble, or
to
an int using Integer.parseInt.
- You should handle the case where
request.getParameter() returns
null. This is especially
true of radio buttons, checkboxes, and selection lists.
- Sometimes there will be multiple values for the same name (for
example,
a selection box that allows multiple items to be selected, or a series
of
text input fields all with the same name)
- To handle this situation, use getParameterValues()
method. This method returns an array of strings.
- e.g. String[] selections =
request.getParameterValues("selectionbox");
- Expanded example:
- a form was added to allow the user to enter the years,
prinicple
ranges, and rate ranges.
- code was added to retrieve this information and load the
variables.
- bolded type shows the form and parameter retrieval code.
- return values for controls:
- A checkbox will return its value if it is checked, otherwise null is returned.
- Radio button will return the value of the button that is turned
on, if no button by that name is on,
then null is returned.
- Buttons will return their value.
- Text boxes and TextAreas will return the text typed in by
the user or an
empty string if no text was entered.
- Selection boxes will return their values of the selected
options in the array of strings. if no
options are selected, null is returned.
- If the name does not exist, then null is returned
- Other notes: TextAreas will send the end of line
characters from the form to the JSP. If the JSP wants to echo this to
the screen in HTML format, then the end of lines need to be converted
to <br> tags. Special characters (& < > and
spaces) should also be converted (this can come from both text and
textareas). Use the replaceAll method of the String object to do
this. Click
here for all the special characters
- & - &amb;
- < - <
- > - >
- space -
- " - "
- ' - '
- \n - <br>
<%!
String
fixInput(String input)
{
String
output = input.replaceAll("&", "&"); // replace
ampersands (do this
first)
output =
output.replaceAll(" ", " "); // replace space
output =
output.replaceAll("<", "<"); // replace <
output =
output.replaceAll(">", ">"); // replace >
output =
output.replaceAll("\r\n", "<br>"); // replace carriage return
sequence, end of line sequence
output =
output.replaceAll("\n", "<br>"); // replace end of line
output =
output.replaceAll("'", "'"); // replace single quote
output =
output.replaceAll("\"", """); // replace double quote
return
output;
}
%>
Passing data through URLs
- Sometimes you will want to invoke a jsp and pass data to it from
a
link on a web page (without using a form).
- To pass the data, you simply add a question mark following the
web
page name, the add sets of parameter
name = value pairs separated by ampersands. E.g.
<a href =
"ProductList.jsp?name=jack
hammer&price=104.99&sku=10000">add</a>
- In the example above, ProducList.jsp is called with three
parameters.
The scriplet code in the jsp can access this parameters in the normal
way
- String productname = request.getParameter("name"); // get
the
product name
- String sku = request.getParameter("sku"); // get the
product
sku
- This is handy if you don't want to use a form type of interface.
- Note,URLS don't like spaces and new line characters,
therefore if your data contains spaces, then these need to be
replaced with + (some browser will use a %20 intead of a plus sign), if
your
data contains end of lines, then you need to replace them with %0D%0A
Mortgage.HTML
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<title>Mortgage
Calculator</title>
<meta
http-equiv="Content-Type" content="text/html; charset=windows-1252">
</head>
<body>
<H2> Enter parameters, then press submit </h2>
<form action = "basic2.jsp"
method=post name = "inputform" target ="Solution">
<table>
<tr><td>Years for the loan : </td><td><input
type=text name="years" value="30" size=3></td></tr>
<tr><td>First principle amount :
</td><td>$<input type=text name="beginingprinciple"
value="1000.00" size=12></td></tr>
<tr><td>Last principle amount :
</td><td>$<input type=text name="endingprinciple"
value="10000.00" size=12></td></tr>
<tr><td>Principle increment:
</td><td>$<input type=text name="principleincrement"
value="1000.00" size=12></td></tr>
<tr><td>First rate amount : </td><td><input
type=text name="beginingrate" value="1.0"
size=4>%</td></tr>
<tr><td>Last rate amount : </td><td><input
type=text name="endingrate" value="10.0"
size=4>%</td></tr>
<tr><td>Rate increment: </td><td><input
type=text name="rateincrement" value="1.0"
size=4>%</td></tr>
</table>
<input type = "Submit" name = "submitbutton" value = "submit">
<input type = "Reset" name = "resetbutton" value = "reset">
</form>
<p>
<iframe name="Solution" width="600"
height="400"></IFRAME>
</body>
</html>
basic2.jsp
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<html>
<head><title>JSP Page</title></head>
<body>
<%-- <jsp:useBean id="beanInstanceName" scope="session"
class="beanPackage.BeanClassName" /> --%>
<%-- <jsp:getProperty name="beanInstanceName"
property="propertyName" /> --%>
<%!
java.text.DecimalFormat currency = new
java.text.DecimalFormat("$#,###,###,##0.00");
java.text.DecimalFormat interest = new
java.text.DecimalFormat("0.0%");
/*
* Compute monthly payment given principle, yearly interest
rate
* and number of years for the loan
*/
double computeMonthlyPayment(double principle, double rate,
double years)
{
double monthlyRate = rate/12.0;
double payment = principle * monthlyRate / (1 - 1 /
Math.pow(1+monthlyRate,years * 12));
return payment;
}
%>
<h2>Monthly Payment Calculation Table </h2>
<table border = 1>
<%
double beginingRate = .01;// first rate to use in the table
double endingRate = .10; // last rate to use in the table
double rateIncrement = .01; // amount to increment rate each time
double beginingPrinciple = 100000.0; // first principle in table
double endingPrinciple = 500000.0; // last principle
in table
double principleIncrement =100000.0; // amount to increment
principle each time
double years = 30;
//
// Retrieve parameters
//
String syears = request.getParameter("years"); // get the
parameter
if(syears != null) // if its null then don't parse, use
default value
years = Double.parseDouble(syears);
String sbrate = request.getParameter("beginingrate");
if(sbrate != null)
beginingRate = Double.parseDouble(sbrate)/100;
String serate = request.getParameter("endingrate");
if(serate != null)
endingRate = Double.parseDouble(serate)/100;
String sratei = request.getParameter("rateincrement");
if(sratei != null)
rateIncrement = Double.parseDouble(sratei)/100;
String sbprin = request.getParameter("beginingprinciple");
if(sbprin != null)
beginingPrinciple = Double.parseDouble(sbprin);
String seprin = request.getParameter("endingprinciple");
if(seprin != null)
endingPrinciple = Double.parseDouble(seprin);
String sprini = request.getParameter("principleincrement");
if(sprini != null)
principleIncrement =
Double.parseDouble(sprini);
//
// output a row of column headers
//
%>
<tr><th><%= years+"" %> years</th>
<%
for(double principle = beginingPrinciple; principle <=
endingPrinciple; principle += principleIncrement)
{
%>
<th><%= currency.format(principle) %>
</th>
<%
}
%>
</tr>
<%
for(double rate = beginingRate; rate <= endingRate; rate +=
rateIncrement)
{
%>
<tr>
<th> <%= interest.format(rate) %> </th>
<%
for(double principle = beginingPrinciple; principle
<= endingPrinciple; principle += principleIncrement)
{
double payment =
computeMonthlyPayment(principle, rate, years);
%>
<td> <%= currency.format(payment) %> </td>
<%
}
%>
</tr>
<%
}
%>
</table>
</body>
</html>
Adding JavaScript to verify the user input prior to submission
- this final example shows how to add the javascript to verify the
form
prior to submission.
- checkForm java script method was added to do the checking on
the
browser side.
- onsubmit action was added to the form to run checkform prior to
submission
to the server
- bolded text shows additions to prior example
- note, the javascript is in a separate file with a .js extension,
using the src parameter on the script tag allows this file to be
included
- <script type="text/javascript"
src="Mortgage2.js"></script>
- putting your functions in a js file makes your html less
cluttered and more readable
Mortgage2.html
!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<title>Mortgage
Calculator with Javascript</title>
<meta
http-equiv="Content-Type" content="text/html; charset=windows-1252">
<script
type="text/javascript"
src="Mortgage2.js>
</script>
</head>
<body>
<H2> Enter parameters,
then press submit </h2>
<form action = "basic3.jsp"
method=post name = "inputform" onSubmit ="return checkForm()"
target="Solution">
<table>
<tr><td>Years for the loan : </td><td><input
type=text name="years" value="30" size=3></td></tr>
<tr><td>First principle amount :
</td><td>$<input type=text name="beginingprinciple"
value="1000.00" size=12></td></tr>
<tr><td>Last principle amount :
</td><td>$<input type=text name="endingprinciple"
value="10000.00" size=12></td></tr>
<tr><td>Principle increment:
</td><td>$<input type=text name="principleincrement"
value="1000.00" size=12></td></tr>
<tr><td>First rate amount : </td><td><input
type=text name="beginingrate" value="1.0"
size=4>%</td></tr>
<tr><td>Last rate amount : </td><td><input
type=text name="endingrate" value="10.0"
size=4>%</td></tr>
<tr><td>Rate increment: </td><td><input
type=text name="rateincrement" value="1.0"
size=4>%</td></tr>
</table>
<input type = "Submit" name = "submitbutton" value = "submit">
<input type = "Reset" name = "resetbutton" value = "reset">
</form>
<p>
<iframe name="Solution"
width="600" height="400"></IFRAME>
</body>
</html>
Mortgage2.js
function checkForm()
{
var valid = true;
var message = "Errors: \n";
var bp=0, ep=0, pi=0, br=0, er=0, ri=0;
with(document.inputform)
{
if(years.value == "" || isNaN(years.value))
{
valid = false;
message = message + "years field
is invalid\n";
}
else
{
var y = parseFloat(years.value);
if(y <= 0)
{
valid = false;
message = message +
"years must be greater than 0\n";
}
}
if(beginingprinciple.value == "" ||
isNaN(beginingprinciple.value))
{
valid = false;
message = message + "first
principle field is invalid\n";
}
else
{
bp = parseFloat(beginingprinciple.value);
if(bp <= 0)
{
valid = false;
message = message +
"first principle must be greater than 0\n";
}
}
if(endingprinciple.value == "" ||
isNaN(endingprinciple.value))
{
valid = false;
message = message + "last
principle field is invalid\n";
}
else
{
ep = parseFloat(endingprinciple.value);
if(ep <= 0 || ep < bp)
{
valid = false;
message = message +
"last principle must be greater first principle\n";
}
}
if(principleincrement.value == "" ||
isNaN(principleincrement.value))
{
valid = false;
message = message + "principle
increment field is invalid\n";
}
else
{
pi =
parseFloat(principleincrement.value);
if(pi <= 0)
{
valid = false;
message = message +
"principle increment must be greater than 0\n";
}
}
if(beginingrate.value == "" ||
isNaN(beginingrate.value))
{
valid = false;
message = message + "first rate
field is invalid\n";
}
else
{
br = parseFloat(beginingrate.value);
if(br <= 0)
{
valid = false;
message = message +
"first rate must be greater than 0\n";
}
}
if(endingrate.value == "" ||
isNaN(endingrate.value))
{
valid = false;
message = message + "last rate
field is invalid\n";
}
else
{
er = parseFloat(endingrate.value);
if(er <= 0 || er < br)
{
valid = false;
message = message +
"last rate must be greater first rate\n";
}
}
if(rateincrement.value == "" ||
isNaN(rateincrement.value))
{
valid = false;
message = message + "rate
increment field is invalid\n";
}
else
{
ri = parseFloat(rateincrement.value);
if(ri <= 0)
{
valid = false;
message = message +
"rate increment must be greater than 0\n";
}
}
}
if(!valid)
alert(message);
return valid;
}
Basic3.jsp
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<html>
<head><title>JSP Page</title></head>
<body>
<%-- <jsp:useBean id="beanInstanceName" scope="session"
class="beanPackage.BeanClassName" /> --%>
<%-- <jsp:getProperty name="beanInstanceName"
property="propertyName" /> --%>
<%!
java.text.DecimalFormat currency = new
java.text.DecimalFormat("$#,###,###,##0.00");
java.text.DecimalFormat interest = new
java.text.DecimalFormat("0.0%");
/*
* Compute monthly payment given principle, yearly interest
rate
* and number of years for the loan
*/
double computeMonthlyPayment(double principle, double rate,
double years)
{
double monthlyRate = rate/12.0;
double payment = principle * monthlyRate / (1 - 1 /
Math.pow(1+monthlyRate,years * 12));
return payment;
}
%>
<h2>Monthly Payment Calculation Table </h2>
<table border = 1>
<%
double beginingRate = .01;// first rate to use in the table
double endingRate = .10; // last rate to use in the table
double rateIncrement = .01; // amount to increment rate each time
double beginingPrinciple = 100000.0; // first principle in table
double endingPrinciple = 500000.0; // last principle
in table
double principleIncrement =100000.0; // amount to increment
principle each time
double years = 30;
//
// Retrieve parameters
//
String syears = request.getParameter("years"); // get the
parameter
if(syears != null) // if its null then don't parse, use
default value
years = Double.parseDouble(syears);
String sbrate = request.getParameter("beginingrate");
if(sbrate != null)
beginingRate = Double.parseDouble(sbrate)/100;
String serate = request.getParameter("endingrate");
if(serate != null)
endingRate = Double.parseDouble(serate)/100;
String sratei = request.getParameter("rateincrement");
if(sratei != null)
rateIncrement = Double.parseDouble(sratei)/100;
String sbprin = request.getParameter("beginingprinciple");
if(sbprin != null)
beginingPrinciple = Double.parseDouble(sbprin);
String seprin = request.getParameter("endingprinciple");
if(seprin != null)
endingPrinciple = Double.parseDouble(seprin);
String sprini = request.getParameter("principleincrement");
if(sprini != null)
principleIncrement =
Double.parseDouble(sprini);
//
// output a row of column headers
//
%>
<tr><th><%= years+"" %> years</th>
<%
for(double principle = beginingPrinciple; principle <=
endingPrinciple; principle += principleIncrement)
{
%>
<th><%= currency.format(principle) %>
</th>
<%
}
%>
</tr>
<%
for(double rate = beginingRate; rate <= endingRate; rate +=
rateIncrement)
{
%>
<tr>
<th> <%= interest.format(rate) %> </th>
<%
for(double principle = beginingPrinciple; principle
<= endingPrinciple; principle += principleIncrement)
{
double payment =
computeMonthlyPayment(principle, rate, years);
%>
<td> <%= currency.format(payment) %> </td>
<%
}
%>
</tr>
<%
}
%>
</table>
</body>
</html>