JavaScript EE, part 1th: Running JavaScript files on the server side

Source: Internet
Author: User
Tags eval vars java se

The thrust of this series of articles is to combine JavaScript with java™ code on the server to be able to use the same JavaScript routines on both the server and the client. In addition, the techniques shown in this series will allow you to maintain the same code base for AJAX clients and non-AJAX clients. Because most of the code on the server side is still written in the Java language, it is necessary to expose these Java Platform, Enterprise Edition (Java EE) features to JavaScript. In this series, you'll learn how to run JavaScript files on the server side, how to invoke remote JavaScript functions with Ajax, and how to use this Java scripting API with JavaServer Pages (JSP) technology.

Typical AJAX applications typically use JavaScript on the client side and often use a different language on the server, such as Java. As a result, developers must implement some of these routines two times, one for using JavaScript in a Web browser, and another for using a different language on the server. This dual-coding problem can actually be avoided by combining JavaScript with server-side Java code, while full support for scripting languages can be obtained through the Javax.script API. In addition, Java SE Development Kit (JDK) 6 already contains Mozilla's Rhino JavaScript engine, which means you will not have to make any settings.

In the first article in this series, you will use a simple script run program to execute JavaScript files within a jave EE application. These scripts will be able to access the so-called "implicit objects" that are used in JSP pages, such as application, session, request, and response. Most of the examples in this article contain reusable code, so that you can easily apply JavaScript to the server in your own application.

Using the Javax.script API

This section gives an overview of the Javax.script API, showing how to execute scripts to access Java objects, call JavaScript functions from Java code, and implement caching mechanisms for the compiled script.

Execute script

The Javax.script API is simple. You can create a Scriptenginemanager instance, and with this example you can get the ScriptEngine object in either of the following ways (see Listing 1):

Getenginebyname ()

Getenginebyextension ()

Getenginebymimetype ()

Listing 1. Get a ScriptEngine instance

import javax.script.*;
...
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
...
engine.eval(...);

In addition, a list of available scripting engines can be obtained by getenginefactories (). Currently, only the JavaScript engine is bundled with JDK 6, but Scriptenginemanager implements a discovery mechanism to discover third-party engines that support JSR-223 scripting for the Java platform (see Resources )。 Just put the script engine jar file into the CLASSPATH.

After you get the Javax.script.ScriptEngine instance, you can invoke eval () to execute the script. You can also export a Java object as a script variable, during which you pass the bindings instance to the eval () method. The Scriptdemo.java example shown in Listing 2 exports two variables named Demovar and STRBUF, executes demoscript.js scripts, and then lets these variables output their modified values.

Listing 2. Scriptdemo.java sample

Package Jsee.demo;
Import javax.script.*;
Import java.io.*;
public class Scriptdemo {
public static void Main (String args[]) throws Exception {
Get the JavaScript engine
Scriptenginemanager manager = new Scriptenginemanager ();
ScriptEngine engine = Manager.getenginebyname ("JavaScript");
Set JavaScript variables
Bindings VARs = new Simplebindings ();
Vars.put ("Demovar", "Value set in Scriptdemo.java");
Vars.put ("Strbuf", New StringBuffer ("string buffer");

Run Demoscript.js
Reader Scriptreader = new InputStreamReader (
ScriptDemo.class.getResourceAsStream ("Demoscript.js"));
try {
Engine.eval (Scriptreader, VARs);
finally {
Scriptreader.close ();
}

Get JavaScript variables
Object Demovar = Vars.get ("Demovar");
System.out.println ("[Java] Demovar:" + Demovar);
System.out.println ("Java object:" + Demovar.getclass (). GetName ());
System.out.println ();
Object strbuf = Vars.get ("Strbuf");
System.out.println ("[Java] Strbuf:" + strbuf);
System.out.println ("Java object:" + Strbuf.getclass (). GetName ());
System.out.println ();
Object Newvar = Vars.get ("Newvar");
System.out.println ("[Java] Newvar:" + Newvar);
System.out.println ("Java object:" + Newvar.getclass (). GetName ());
System.out.println ();
}

}

The Demoscript.js file (shown in Listing 3) contains a printtype () function that can be used to output the type of each script variable. This example invokes the Append () method of the Strbuf object, modifies the Demovar value, and sets a new variable script named Newvar.

If the object passed to Printtype () has a getclass () method, it must be a Java object whose class name is obtained by Obj.getclass (). Name. This JavaScript expression calls the GetName () method of the Java.lang.Class instance of this object. If this object does not have GetClass, then Printtype () invokes the Tosource () method, which is available to all JavaScript objects.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.