|
Bean with Indexed Properties and Accessing Indexed values through JSP Bean tags |
|
|
In this example, A component is built that can perform statistical calculations on a series of numbers. The numbers themselves are stored in a single, indexed property. Other properties of Bean hold the value of statistical calculations, like the average or the sum.
JSP Bean tags deal exclusively with scalar properties, the only way to interact with indexed properties such as these is through JSP scriptlets in the body of the <jsp:useBean> tag to pass an array of integers to the Bean’s numbers property.
<jsp:useBean id="stat" class="DemoStatBean">
<%
double[] mynums = {100,200,300,400,500)
stat..setNumbers(mynums);
%>
</jsp:useBean>
<html>
<body>
The average of
<%
double[] numbers = stat.getNumbers();
for(int i=0;i<numbers;i++){
if(i!=numbers.length)
out.print(numbers[i] + ",");
else
out.println("" + numbers[i]);
}
%>
is equal to <jsp:getProperty name = "stat" property ="average"/>
</body>
</html>
|
DemoStatBean.java
import java.util.*;
public class DemoStatBean {
public double[] numbers;
public DemoStatBean(){
numbers = new double[0];
}
public double getAverage(){
double sum = this.getSum();
if(sum==0)
{
return 0;
}
else
return sum/numbers.length;
}
private double getSum() {
double sum = 0;
for(int i=0; i<numbers.length;i++){
sum+=numbers[i];
}
return sum;
}
public double[] getNumbers() {
return numbers;
}
public void setNumbers(double[] numbers) {
this.numbers = numbers;
}
public double getNumbers(int index){
return numbers[index];
}
public void setNumbers(int index,double value){
numbers[index]=value;
}
}
|
Related Tips
|
Page 1 of 0 ( 0 comments )
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.