
Use this procedure to create a JavaBean that retrieves the home interface of the Calculator session bean by performing a lookup operation in the naming system, and which invokes the bean's business methods. The JavaBean also passes the numbers entered in the JSP to the enterprise bean and then returns the result to the JSP.
You have created the Web module project CalculatorWeb, and you have added the EJB module project CalculatorEjb to its build path.
Creating the JavaBean class
The package is created in CalculatorWebt/source directory.
The wizard generates a new java file CalcProxy.java and opens the Java editor automatically, displaying the generated content of the new class.
Adding Source Code
public class CalcProxy {
private Calculator calc;
public void init() throws Exception {
//Lookup the enterprise bean
try {
InitialContext ctx = new InitialContext();
Object ob = ctx.lookup("java:comp/env/ejb/CalculatorBean");
CalculatorHome home = ( CalculatorHome ) PortableRemoteObject.narrow( ob, CalculatorHome.class );
//Initialize the enterprise bean
calc = home.create();
} catch ( Exception e ) {
throw new Exception("Error instantiating Calculator EJB" + e.toString());
}
} public CalcProxy() throws Exception {
init();
}public float getResult( String firstNumber, String secondNumber, String expression ) throws Exception {
float result = 0;
try {
if ( firstNumber != null && secondNumber != null ) {
//Parse the input parameters
float first = Float.parseFloat( firstNumber );
float second = Float.parseFloat( secondNumber );
int expr = Integer.parseInt( expression );
//Invoke the relevant method of the enterprise bean
switch ( expr ) {
case 1:
result = calc.multiply( first, second );
break;
case 2:
result = calc.divide( first, second );
break;
case 3:
result = calc.add( first, second );
break;
case 4:
result = calc.subtract( first, second );
break;
}
}
}catch (Exception re){
throw new Exception("Fill in all required fields with appropriate values!");
}
//Return the result of the calculation
return result;
}The appropriate import statements are added to the source code.
The JavaBean CalcProxy is also automatically compiled in CalculatorWebt/bin directory. To navigate to this directory, choose the Navigator view.
You have created and completely implemented the JavaBean CalcProxy, which will serve as the controller part of your Calculator application.
Next step:
Next you develop the Calculator JSP .