The Java EE 5 Tutorial

Coding the converter Web Client

The statements (in bold in the following code) for locating the business interface, creating an enterprise bean instance, and invoking a business method are nearly identical to those of the application client. The parameter of the lookup method is the only difference.

The classes needed by the client are declared using a JSP page directive (enclosed within the <%@ %> characters). Because locating the business interface and creating the enterprise bean are performed only once, this code appears in a JSP declaration (enclosed within the <%! %> characters) that contains the initialization method, jspInit, of the JSP page. The declaration is followed by standard HTML markup for creating a form that contains an input field. A scriptlet (enclosed within the <% %> characters) retrieves a parameter from the request and converts it to a BigDecimal object. Finally, a JSP scriptlet invokes the enterprise bean’s business methods, and JSP expressions (enclosed within the <%= %> characters) insert the results into the stream of data returned to the client.

<%@ page import="converter.ejb.Converter,
            java.math.*, javax.naming.*"%>

    private Converter converter = null;
    public void jspInit() {
        try {
            InitialContext ic = new InitialContext();
            converter = (Converter)
        } catch (Exception ex) {
            System.out.println("Couldn’t create converter bean."+

    public void jspDestroy() {
        converter = null;

    <body bgcolor="white">
        <p>Enter an amount to convert:</p>
        <form method="get">
            <input type="text" name="amount" size="25">
            <input type="submit" value="Submit">
            <input type="reset" value="Reset">

            String amount = request.getParameter("amount");
            if ( amount != null && amount.length() > 0 ) {
                BigDecimal d = new BigDecimal(amount);

                BigDecimal yenAmount = converter.dollarToYen(d);
        <%= amount %> dollars are  <%= yenAmount %>  Yen.
                BigDecimal euroAmount =
        <%= amount %> Yen are <%= euroAmount %>  Euro.