We will see how the bean tag works
using a currency converter example. In this example we will convert dollars to
rupees. We do this using the CurrencyConverter JavaBeans class.
The CurrencyConverter class.
package vaannila;
public class CurrencyConverter {
private float rupees;
private float dollars;
public float getRupees() {
return dollars * 50;
}
public void setRupees(float rupees) {
this.rupees = rupees;
}
public float getDollars() {
return rupees/50 ;
}
public void setDollars(float dollars) {
this.dollars = dollars;
}
}
The next step is to create an
instance of the CurrencyConverter bean in the jsp page using the bean tag. We can either use the bean tag
to push the value onto the ValueStack or we can set a top-level reference to it in the ActionContext. Let's see one by
one.
First we will see how we can do this
by pushing the value onto the ValueStack. The index.jsp page contains the following code.
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
<title>Bean Tag
Example</title>
</head>
<body>
<s:bean name="vaannila.CurrencyConverter">
<s:param name="dollars" value="100" />
100 Dollars = <s:property value="rupees" /> Rupees
</s:bean>
</body>
</html>
The name attribute of the bean tag hold the fully qualified class name of the
JavaBean. The param tag is used to set the dollar value. We now use the property tag to retrive the equivalent value in rupees.
The CurrencyConverter bean will resides on the ValueStack till the duration of the bean tag. So its important that we use the
property tag within the bean tag.
When you execute
the example the following page is displayed.
Now we will see how we can do the
same by creating a top-level reference to the bean in theActionContext. We do this using
the following code.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
<title>Bean Tag
Example</title>
</head>
<body>
<s:bean name="vaannila.CurrencyConverter" var="converter">
<s:param name="dollars" value="100"></s:param>
</s:bean>
100 Dollars = <s:property value="#converter.rupees" /> Rupees
</body>
</html>
To create an instance of the bean in
the ActionContext we need to specify the instance name
using thevar attribute of the bean tag. Here our instance name is converter. Once we do this
we can access the bean values outside the bean tag. Since the value is in the ActionContext we use the # operator to refer it.
No comments:
Post a Comment