ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button

The Mustang Meets the Rhino: Scripting in Java 6
Pages: 1, 2, 3, 4

Web Development

One of the more ambitious goals of the JSR 223 specification is to provide for integration of non-Java scripting pages (such as PHP) into a Java web application. This is designed to allow both non-Java scripting pages to be integrated as part of a Java web application, but also for Java classes to be invoked from the scripting pages. For example, the following PHP code shows how Java objects can be used from within a PHP page:




    //instantiate a java object

    $javadate = new Java( java.util.Date );

    //call a method
    $date =$javadate->toString();

    //display return value
    echo($date);

More importantly for integration into a Java web application server, the specification provides a standard API for accessing and modifying the servlet container session data:


    <ul>
    <?
      //display session attributes in table
      $enum=$request->getSession()->getAttributeNames();
      foreach ($enum as $name) {
        $value = $request->getSession()->getAttribute($name);
        print("<li>$name = $value<li>");
      }
    ?>
    </ul>

The implications of this integration are far-reaching. It is now possible to code web applications in a J2EE environment not only in Java, but also with other scripting languages, using Java as a powerful cross-platform architecture. And existing pages or applications written in other scripting languages can now be integrated with J2EE applications with little effort.

Conclusion

Scripting languages are hailed by some as the answer to all our programming woes and decried by others as encouraging unstructured and unmaintainable code. As with any tool, scripting can be used or abused. Script languages are flexible, easy to learn and fast to write. However, they have only limited support in Java IDEs, are difficult to test using traditional testing frameworks such as JUnit, and errors may not appear until runtime. Nevertheless, correct and appropriate use of scripting can certainly make life easier in many cases. Scripting should be considered in situations such as:

  • A means of extending or customizing applications.
  • A convenient way of implementing flexible (and sometimes complex) business rules that may often change.

Overall, scripting support undoubtedly offers a rich new addition to the Java developer's toolbox.

Resources

John Ferguson Smart is a freelance consultant specializing in Enterprise Java, Web Development, and Open Source technologies, currently based in Wellington, New Zealand.


Return to ONJava.com.