Scenario: Creating a Bean Scripting Framework application

 

Scenario description

Programming skills in JavaScript code are more prevalent than programming skills using JSP (JSP) tags. Using the Bean Scripting Framework, JavaScript programmers can gradually introduce JSP tags in their JavaScript applications without completely rewriting the source code. The BSF method not only reduces the potential of programming errors, but also provides a painless way to learn a new technology.

The following scenario illustrates how to implement a BSF application using JavaScript within JSP tags.

 

Developing the BSF application

At ABC elementary school, John Doe teaches third grade mathematics. He wants to help his students memorize their multiplication tables, and thinks a small Web-based quiz could help meet his objective. However, John Doe only knows JavaScript.

Using the Bean Scripting Framework to help leverage his JavaScript skills, John Doe creates two JSP files, multiplication_test.jsp and multiplication_scoring.jsp.

In the multiplication_test.jsp file, John Doe uses both client-side and server-side JavaScript code to generate a test of 100 random multiplication questions, displayed using a three minute timer. He then writes the multiplication_scoring.jsp file to read the data submitted by the multiplication_test.jsp file and to generate the scoring results.

John Doe creates the following two files

multiplication_test.jsp...
<html>
<head>
<title>Multiplication Practice Test</title>
<script language="javascript">
var countMin=3;
var countSec=0;
function updateDisplay (min, sec) {
    var disp;
    if (min <= 9) disp = " 0";
    else disp = " ";
    disp += (min + ":");
    if (sec <= 9) disp += ("0" + sec);
    else disp += sec;
    return(disp); 
}
function countDown() {
    countSec--;
    if (countSec == -1) { 
        countSec = 59; 
        countMin--; 
    }
    document.multtest.counter.value = updateDisplay(countMin, countSec);
    if((countMin == 0) &&(countSec == 0)) document.multtest.submit();
    else var down = setTimeout("countDown();", 1000); 
}
</script>
</head>
<body bgcolor="#ffffff" onLoad="countDown();">
<%@ page language="javascript" %>
<h1>Three Minute Multiplication Drill</h1>
<hr>
<h2>Remember: this is an opportunity to excel!</h2>
<p>
<form method="POST" name="multtest" action="multiplication_scoring.jsp">
<div align="center">
<table>
<tr>
<td>
<h3>Time left: 
<input type="text" name="counter" size="9" value="03:00" readonly>
</h3>
</td>
<td>
<input type="submit" value="Submit for scoring!">
</td>
</tr>
</table>
<table border="1">
<%
var newrow = 0;
var q_num = 0;
function addQuestion(num1, num2) {
    if (newrow == 0) out.println("<tr>");
    out.println("<td>");
    out.println(num1 + " x " + num2 + " = ");
    out.println("</td><td>");
    out.print("<input name=\"" + q_num + "|" + num1 + ":" + num2 + "\" ");
    out.println("type=\"text\" size=\"10\">");
    out.println("</td>");
    if (newrow == 3) {
        out.println("</tr>");
        newrow = 0;
    }
    else newrow++;
    q_num++;
}
for (var i = 0; i < 100; i++) {
    var rand1 = Math.ceil(Math.random() * 12);
    var rand2 = Math.ceil(Math.random() * 12);
    addQuestion(rand1, rand2);
}
%>
</table>
</div>
</form>
</body>
</html>

multiplication_scoring.jsp...
<html>
<head>
<title>Multiplication Practice Test Results</title>
</head>
<body bgcolor="#ffffff">
<%@ page language="javascript" %>
<h1>Multiplication Drill Score</h1>
<hr>
<div align="center">
<table border="1">
<tr><th>Problem</th><th>Correct Answer</th><th>Your Answer</th></tr>
<%
var total_score = 0;
function score (current, pos1, pos2) {
    var multiplier = current.substring(pos1 + 1, pos2);
    var multiplicand = current.substring(pos2 + 1, current.length()); 
    var your_product = request.getParameterValues(current)[0];
    var true_product = multiplier * multiplicand;
    out.println("<tr>");
    out.println("<td>" + multiplier + " x " + multiplicand + " = </td>");
    out.println("<td>" + true_product + "</td>");
    if (your_product == true_product) {
        total_score++;
        out.print("<td bgcolor=\"\#00ff00\">");
    }
    else {
        out.print("<td bgcolor=\"\#ff0000\">"); 
    }
    out.println(your_product + "</td>");    
    out.println("</tr>");
}
var equations = request.getParameterNames();
while(equations.hasMoreElements()) {
   var currElt = equations.nextElement();
   var splitPos1 = currElt.indexOf("|");
   var splitPos2 = currElt.indexOf(":");
   if (splitPos1 >=0 && splitPos2 >= 0) score(currElt, splitPos1, splitPos2);
}
%>
</table>
<h2>Total Score: <%= total_score %></h2>
<h3><a href="multiplication_test.jsp">Try again?</a></h3>
</div>
</body>
</html>

Follow these steps to see how John Doe uses BSF to implement JavaScript in a JSP application:

  1. Give your files a .jsp extension.

  2. Use server-side JavaScript code in your application.

    The multiplication_test.jsp file incorporates both client-side and server-side JavaScript. Server-side JavaScript is similar to client-side JavaScript; the primary difference consists of using a different set of objects. Whereas client-side Javascript programmers invoke document and window objects, server-side JavaScript programmers, using the Bean Scripting Framework, invoke a set of objects provided by the JSP technology. Also, client-side scripts are enclosed in <script> tags, but server-side scripts use JSP scriptlet and expression tags.

  3. Examine the following blocks of code

    <script language="javascript">
    var countMin=3;
    var countSec=0;
    function updateDisplay (min, sec) {
        var disp;
        if (min <= 9) disp = " 0";
        else disp = " ";
        disp += (min + ":");
        if (sec <= 9) disp += ("0" + sec);
        else disp += sec;
        return(disp); 
    }
    function countDown() {
        countSec--;
        if (countSec == -1) { 
            countSec = 59; 
            countMin--; 
        }
        document.multtest.counter.value = updateDisplay(countMin, countSec);
        if((countMin == 0) && (countSec == 0)) document.multtest.submit();
        else var down = setTimeout("countDown();", 1000); 
    }
    </script>
    ....
    <body bgcolor="#ffffff" onLoad="countDown();">
    ...
    <form method="POST" name="multtest" action="multiplication_scoring.jsp">
    ...
    <input type="text" name="counter" size="9" value="03:00" readonly>
    ...
    
    

    The JavaScript code contained in the <script> block implements a timer set within the <input> field named counter. The onLoad event handler in the <body> tag causes the browser to load and execute the code when the the page is loaded.

    The document.multtest.submit() statement causes the form named multtest to be submitted when the timer expires.

  4. Identify the code to the BSF function.

    The following code example, from the multiplication_test.jsp file, displays the use of a JSP directive. This directive tells the WAS BSF function that this file is using the JavaScript language, and that the JavaScript code is enclosed by the <% ... %> scriptlet tags. The out implicit JSP object in this code example, creates the body section of a table from 100 randomly generated questions

    ...
    <%@ page language="javascript" %>
    ...
    <%
    var newrow = 0;
    var q_num = 0;
    
    function addQuestion(num1, num2) {
        if (newrow == 0) out.println("<tr>");
    
        out.println("<td>");
        out.println(num1 + " x " + num2 + " = ");
        out.println("</td><td>");
        out.print("<input name=\"" + q_num + "|" + num1 + ":" + num2 + "\" ");
        out.println("type=\"text\" size=\"10\">");
        out.println("</td>");
    
        if (newrow == 3) {
            out.println("</tr>");
            newrow = 0;
        }
        else newrow++;
    
        q_num++;
    }
    
    for (var i = 0; i < 100; i++) {
        var rand1 = Math.ceil(Math.random() * 12);
        var rand2 = Math.ceil(Math.random() * 12);
    
        addQuestion(rand1, rand2);
    }
    
    %>
    ...
    
    

  5. Read the results.

    To score the results of the practice drill, John Doe uses the request implicit JSP object in the multiplication_scoring.jsp file to obtain the POST data created within the <form> tags in the multiplication_test.jsp file.

    The multiplication_scoring.jsp file uses the POST data to build an output file containing the original question, the student's answer, and the correct answer, and then prints the text in a table format using the out implicit object.

    The following code example from the multiplication_scoring.jsp file illustrates the use of the request and out JSP objects

    ...
    <%@ page language="javascript" %>
    ...
    <%
    var total_score = 0;
    function score (current, pos1, pos2) {
        var multiplier = current.substring(pos1 + 1, pos2);
        var multiplicand = current.substring(pos2 + 1, current.length()); 
        var your_product = request.getParameterValues(current)[0];
        var true_product = multiplier * multiplicand;
        out.println("<tr>");
        out.println("<td>" + multiplier + " x " + multiplicand + " = </td>");
        out.println("<td>" + true_product + "</td>");
        if (your_product == true_product) {
            total_score++;
            out.print("<td bgcolor=\"\#00ff00\">");
        }
        else {
            out.print("<td bgcolor=\"\#ff0000\">"); 
        }
        out.println(your_product + "</td>");    
        out.println("</tr>");
    }
    var equations = request.getParameterNames();
    while(equations.hasMoreElements()) {
       var currElt = equations.nextElement();
       var splitPos1 = currElt.indexOf("|");
       var splitPos2 = currElt.indexOf(":");
       if (splitPos1 >=0 && splitPos2 >= 0) score(currElt, splitPos1, splitPos2);
    }
    
    %>
    ...
    <h2>Total Score: <%= total_score %></h2>
    ...
    
    
    Note: Although using separate scriptlet blocks of code for different portions of a conditional expression is common in JSP files implemented in Java, it is invalid for JSP files implemented using JavaScript through the Bean Scripting Framework. The JavaScript code must be entirely contained within the scriptlet tags.

    The following code example illustrates invalid usage

    <% if (pass == 0) %>
        <i>pass is true</i>
    <% else %>
        <i>pass is not true</i>
    
    

 

Deploying the BSF application

You assemble and deploy BSF applications in the same manner as JSP applications. Review the Assembling applications with the Assembly Toolkitarticle for more information.

Deploy the BSF code examples in WAS to view this applications processing and output. Use the following quick steps to deploy the application.

The intent of these "quick steps" is to provide you with instant application output. However, the supported method for deployment is the same as for standard JSP files.

  1. Use the DefaultApplication to add your BSF files.

    Copy your .jsp files to the DefaultApplication directory...

    <app server install directory>/installedApps/<node name>/DefaultApplication.ear/DefaultApplication.war

  2. Start the appserver.

  3. Open a browser and request your BSF application.

    Use the following URL to request your application...

    http://hostName:9080/<jspFileName>.jsp

 

See Also

Bean Scripting Framework
Example: Converting JavaScript source to the Bean Scripting Framework
Example: Bean Scripting Framework code example
Webapplications: Resources for learning