JSP and JavaBeans, why can't I use a bean method's return value?

42 views Asked by At

I am learning JSP and javabeans. I have written a simple web app that calculates loan repayments. The app correctly sets the bean's fields with user input (from a form). The bean also contains a method calculatePayment() which for some reason I can't call from the JSP page. I have searched the net and reviewed the code with no success. Any help would be welcome.

The server log reports:

org.apache.jasper.JasperException: An exception occurred processing [/index.jsp] at line [56]

53:         <table>
54:             <tr>
55:                 <td>Annual payment is</td>
56:                 <td>${loanBean.calculatePayment()}</td>
57:             </tr>
58:         </table>
59:     </body>

and:

Root Cause:

jakarta.el.ELException: java.lang.NullPointerException: Cannot invoke "String.trim()" because "in" is nul

Here are snippets of the code:

the calculatePayment() method in LoanBean:

public String calculatePayment() {
    double P = Double.parseDouble(loanAmount);
    double r = Double.parseDouble(rate);
    double t = Double.parseDouble(term);
        
    double A = P*(Math.pow(1 + r, t));
        
    DecimalFormat df = new DecimalFormat("#.##");
    String num_string = df.format(A);
    return num_string;    
}

and my JSP page - instantiating the bean and specifying fields to set:

<%@page contentType="text/html" pageEncoding="UTF-8" session="true"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Klausen_Chapter5_Problem1_LoanCalculator</title>
    </head>
    <body>
        <jsp:useBean id="loanBean"  scope="session"  class="loancalculator.beans.LoanBean"/>

        <jsp:setProperty name="loanBean" property="arrangementFee"/>
        <jsp:setProperty name="loanBean" property="loanAmount"/>
        <jsp:setProperty name="loanBean" property="rate"/>
        <jsp:setProperty name="loanBean" property="term"/>
        <h1>Loan Calculation</h1>
        <form name="form1"  method="post">
            <table>
                <tr>
                    <td>Arrangement fee :</td>
                    <td><input type="text"  name="arrangementFee" value="${loanBean.arrangementFee}"/>
                </tr>
                <tr>
                    <td>Enter loan amount :</td>
                    <td><input type="text"  name="loanAmount"  value="${loanBean.loanAmount}"</td>
                </tr>
                                     -----   more rows and input elements ----

                <tr><td></td>
                    <td><input type="submit"  value="Clear"/>
                        <input type="submit"  value="Calculate"/>
                    </td>
                </tr>
            </table>
        </form>
        
        <br><br>
        <table>
            <tr>
                <td>Annual payment is</td>
                <td>${loanBean.calculatePayment()}</td>
            </tr>
        </table>
    </body>
</html>

I've looked carefully at the code and searched the net for answers but to no avail.

2

There are 2 answers

1
azeemofwalsall On BEST ANSWER

I have solved the problem. As RomanC has said, the bean fields are not set until the calculate (submit) button is clicked. As a result, the values used in method calculatePayment() will all be null.

Therefore I have modified the method to check for null values:

public String calculatePayment() {
    
        if (loanAmount == null || rate == null || term == null) {
            return "";
        } else {
            // parse strings to double           
            double P = Double.parseDouble(loanAmount);
            double r = (Double.parseDouble(rate)/100);
            double t = Double.parseDouble(term);
            
            // calculate annual payment
            double A = P*(Math.pow(1 + r, t));
            
            // format the result to 2dp
            DecimalFormat df = new DecimalFormat("#.##");
            String numstring = df.format(A);
            return numstring;
        }
}

Now when the user clicks the calculate button, the bean fields will not be zero and the else part of the if - block will be called.

1
Roman C On

The variables are set if you submit the form. Before you submit a form the parameters are not set in the request, and a bean is not populated from the request parameters. You cannot use a bean's method from the EL expression before you initialize a bean properly. And you can't initialize a bean with request parameters because the HTTP method used in the form is POST. So, use the GET method to submit a form (which is default)

<form name="form1">
          

and make sure the properties are initialized before you call loanBean.calculatePayment().