I have a small JSP 2.0 application that sends information to a class
file, gets it back and displays it in a web page. The code is below.
Kilowatt.class
--------------------
package electric;
public class Kilowatt
{
private double costKiloWattHours; //example 8.42 which means cents
private double hoursUsedPerYear; //example 653
private double annualCost;
public void setCost(double cost)
{
costKiloWattHours = cost / 100;
}
public void setHours(double hours)
{
hoursUsedPerYear = hours;
}
public double getAnnualCost()
{
annualCost = costKiloWattHours * hoursUsedPerYear;
return annualCost;
}
}
jmElectric.jsp
--------------------
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>electric page</title>
</head>
<body>
<jsp:useBean id="myKilo" scope="page" class="electric.Kilowatt"/>
<jsp:setProperty name="myKilo" property="cost" value="8.42"/>
<jsp:setProperty name="myKilo" property="hours" value="653"/>
The annual cost is: <fmt:formatNumber value="${myKilo.annualCost}"
type="currency"/>
</body>
</html>
As you can see, I use the setProperty tag to send the values to the
class file. My question is how can I turn this into a form so the user
can enter the values? I've tried researching this but haven't been able
to come up with an example. Thanks very much.
dmcquay@gmail.com - 27 Jan 2006 22:45 GMT
I am not familiar with JSP specifically, but I am with PHP and some
others and I think the main idea should be the same.
I believe the JSP stuff is always processed by the server before
sending the result to the user for display. So the only way to tell
the server those properties is to send them with the request for the
page. This could be sent in the url (called a query string) or it
could be sent by an HTML form. Let me know if you need further
explanation on any of that. I don't know how to process the
information from there, but I know it can be done in JSP and that's
probably what you are looking for.
Another simple option would be to just do this with javascript.
Example:
**** CODE ****
<html>
<head>
<title>Annual Cost</title>
<script language="javascript">
function calcCost()
{
var cost = document.getElementById("cost").value;
var hours = document.getElementById("hours").value;
var result = cost * hours;
document.getElementById("result").value = result;
}
</script>
</head>
<body>
Cost: <input type="text" id="cost" /><br />
<input type="text" id="hours" /><br />
Annual Cost: <span id="result"></span><br />
<hr />
<button onclick="javascript:calcCost()">Calculate</button>
</body>
</html>
**** END CODE ****
That is just a bad looking rough outline without currency formatting,
but you get the idea.