17.6 Invoking the business logic of the calculator

To actually use the calculator, you have to invoke the calculate method of the bean when Calculate is clicked.

1. In the Page Designer, select the Calculate button. In the Quick Edit view, select Command in the left pane. Click in the right pane and this sample code appears:
// Type Java code that runs when the component is clicked

// TODO: Return outcome that corresponds to a navigation rule

return "";

2. Replace the generated action code with the code shown in Example 17-1.

Example 17-1 Action code to invoke the calculate method

log("CalculateAction start");
try {
 getCalculator().calculate();
} catch (Exception e) {
 log("Calculator-Exception: "+e.getMessage());
 if (getCalculator().getErrorMessage() == null)
  getCalculator().setErrorMessage("Exception: "+e.getMessage());
} finally {
 log("CalculateAction end"); 
}
return null;

3. Save the calculate.jsp. Open the Calculate.java file and notice that the action code has been added in the doCalcAction method. You can also make further changes either in the Quick Edit view or in the Java class.

4. Select the Calculate button. In the Properties view, click the Show All Attributes icon (). You can see that the action is set to #{pc_Calculate.doCalcAction}. This is the link to the Java code.

5. Rerun the project (Figure 17-27). Perform some calculations. For example, try to multiply 123 by 14.

Figure 17-27 The calculator application showing the results

6. Try the divide operation with values that result in a non-integer result. Notice the exception in the Console. The result is still calculated.
Note: You will implement an error page to display the error message in 17.6.1, Implementing an error page.


Redbooks
ibm.com/redbooks