Tuesday, August 6, 2013

Struts 2 Bean Tag Tutorial

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.
01.package vaannila;
02. 
03.public class CurrencyConverter {
04. 
05.private float rupees;
06.private float dollars;
07. 
08.public float getRupees() {
09.return dollars * 50;
10.}
11.public void setRupees(float rupees) {
12.this.rupees = rupees;
13.}
14.public float getDollars() {
15.return rupees/50 ;
16.}
17.public void setDollars(float dollars) {
18.this.dollars = dollars;
19.}
20. 
21.}
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.
01.<html>
02.<head>
03.<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
04.<title>Bean Tag Example</title>
05.</head>
06.<body>
07.<s:bean name="vaannila.CurrencyConverter">
08.<s:param name="dollars" value="100" />
09.100 Dollars = <s:property value="rupees" /> Rupees
10.</s:bean>
11. 
12.</body>
13.</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.
01.<html>
02.<head>
03.<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
04.<title>Bean Tag Example</title>
05.</head>
06.<body>
07.<s:bean name="vaannila.CurrencyConverter" var="converter">
08.<s:param name="dollars" value="100"></s:param>
09.</s:bean>
10.100 Dollars = <s:property value="#converter.rupees" /> Rupees
11. 
12.</body>
13.</html>
To create an instance of the bean in the ActionContext we need to specify the instance name using the var 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