Remote Scripting using a servlet

Source: Internet
Author: User
Tags abstract documentation html page http post net reference client
Erik Hatcher ( President, Ehatcher Solutions, inc.01 Feb 2001
The users of WEB applications have suffered a dramatic shift in experiences to the world of desktop applications. Many Web applications does not on all mimic the usability, interactivity, and dynamic nature of this is available in typical St Andalone or Client-server desktop applications because of the constraints that HTML and HTTP impose. Here, Erik Hatcher explains how remote scripting can is used to enhance the interactivity and dynamic nature of a Web appl Ication experience.
One of the major drawbacks to WEB applications are that the user experience are typically inferior to that of desktop Ations. Most current WEB applications lack in interactivity because once the browser receives a response to its URL request it is On it own, failing to communicate the server until a hyperlink be clicked or a form is submitted. Techniques such as using JavaScript and DHTML can used to make the browser feel more like a desktop application; Fancier techniques like using Flash, ActiveX, and Java applets can also accomplish this end.

But even with this newer techniques and technologies, the client is still mostly in its own after it receives the content From the WEB server. The technique described in this article offers a solution which allows the browser and WEB server to communicate behind the Scenes. The browser can invoke remote Java servlet methods that enable the user experience to resemble that of a desktop Applicati On, such as populating a Drop-down box dynamically based on the selection of a related Drop-down box (this is, category/su Bcategory), or polling the server for messages and refreshing the display dynamically with continuously content.

Client Sidethere are two popular ways of accomplishing remote method invocation from Web Browser:microsoft remote SCRIP Ting (MSRs) and Brent Ashley ' s JavaScript remote scripting (JSRS). The goal of both is the same:to invoke remote methods and return the results to the browser. Both methods were originally designed to communicate and remote methods in Microsoft ' s Active Server Pages. This article provides a way for both of those methods to communicate with a Java servlet on the server side. Let's get into the architecture details of this techniques.

Redmond scripting Microsoft ' s remote scripting is part of the Visual InterDev development environment. It consists of three pieces:an invisible Java applet, client-side JavaScript, and server-side JavaScript running in Activ E Server Pages. The Java applet handles the communications with the server. The Client-side JavaScript communicates with the applet. The Server-side JavaScript deals with taking the requested parameters and dispatching them to the specified me Thod. The communications are simply HTTP get requests and responses, with the details of the method call sent as query parameter s to the Server-side script. There is very much the said about Microsoft's remote scripting architecture, but that are beyond the scope of this articl E (in).

Figure 1 shows the architecture of Microsoft remote scripting using a servlet on the server-side.

Steps involved in invoking a remote method using Microsoft remote scripting:
The browser executes a JavaScript call to Rsexecute (this resides into a included JavaScript framework provided by Microsof T Visual InterDev). The Remote Scripting applet uses HTTP get to access a special servlet URL on the server, complete with method name and Par Ameters. The servlet returns its xml-like response and the applet receives it. The response is interpreted from the remote scripting JavaScript and returned to the calling code. A Call object are returned, and the actual return value is the the. Return_value property if it is returned successfull Y.

Figure 1. Microsoft Remote Scripting Architecture

JSRs architecturebrent Ashley ' s JavaScript remote scripting accomplishes the same goal using a nifty DHTML trick of inject ing a hidden <IFRAME> or <LAYER> (depending on the browser type) for each concurrent remote scripting call Mad E. The hidden piece is navigated to the remote scripting URL using HTTP get. The result returned from the "server is" HTML with a onLoad JavaScript call to the main window callback function.

Figure 2 shows the architecture of JavaScript remote scripting using a servlet on the server-side.

Steps involved in invoking a remote method using JavaScript remote scripting:
The browser executes a JavaScript call to Jsrsexecute (this resides in the external jsrsclient.js file [click to O Btain JSRs]). Code in Jsrsclient.js creates a <IFRAME> or <LAYER> (or re-uses a existing one) and navigates it to a URL WI th the appropriate parameters. The servlet returns its HTML response and the client receives it. The <BODY> onLoad the returned HTML invokes the specified callback with the returned value.

note:the example in-article shows Microsoft ' s remote scripting being used synchronously, but it could also be used a Synchronously with a callback like the JSRs example. However, JSRs isn't capable of making synchronous method invocations.

Figure 2. Brent Ashley ' s JavaScript Remote scripting architecture

Let's some codethe servlet described below has been to designed support and both. This flexibility'll is demonstrated by allowing the client to toggle between using either method. A single HTML page was created with both the MSRs pieces (JavaScript and applets) and the JSRs (a single external javascript ) piece. Using The category/subcategory idea, the goal are to have a category selection which then determines which subcategory Sele Ctions are available. Here is the HTML <body>:
Listing 1. Category selection
<body onload= "javascript:categorychanged ()" > <form name= "Form1" > <TABLE> <TR> <TH> Remote scripting type:</th> <TD> <input type= "Radio" name= "ClientType" value= "MSRs" >msrs<br/> <input type= "Radio" name= "ClientType" value= "JSRs" Checked>jsrs </TD> </TR> <TR> <TH> category:</th> <TD> <select name= "Category" onchange= "javascript:categorychanged ()" > <option Value= "0" selected>category 0</option> <option value= "1" >category 1</option> <OPTION value= "2 ">category 2</option> <option value=" 3 ">error test</option> </SELECT> </TD> </tr > <TR> <TH>Subcategory:</TH> <TD> <select name= "subcategory" > <!--Need A Placeholder until it can get loaded--> <option value= "-1" selected>---------------------</OPTION> </ select> </TD> </TR> </TABLE> </FORM> </BODY>

Everything about the HTML is straightforward. Note This categorychanged is called when the ' document is loaded and ' The category field is changed by the user. The Categorychanged method is defined as:
Listing 2. Categorychanged method
function categorychanged () {if (document.form1.clienttype[0].checked) {//MSRs var co = rsexecute ("/servlet/rsexample", "Getsubcategories", Document.form1.category.options[document.form1.category.selectedindex].value); if (co.status!= 0) {return;} var subcatstr = Co.return_value; Populatedropdown (SUBCATSTR); else {//JSRs Jsrsexecute ("/servlet/rsexample", Populatedropdown, "Getsubcategories", Document.form1.category.options[document.form1.category.selectedindex].value); } }

Remote scripting now comes in by calling the remote method getsubcategories. Refer to the Microsoft Remote scripting documentation for details of the remote scripting ' call object ' returned from Rsex Ecute (in). The call to Jsrsexecute specifies that Populatedropdown is called when the asynchronous call completes. Refer to the details of the Populatedropdown.

On the server side, the servlet was defined as in Listing 3.

Rsexample Servlet has a static public method named, not coincidentally, getsubcategories. This is, of course, simply a proof-of-concept, but it could easily as extended to do a database lookup of T He subcategories relating to a category. The Getsubcategories function can only deal with a CATID of 0, 1, or 2. The sample code includes a demonstration of invoking this method with a invalid value of 3 ("Error Test" in the category Drop-down). The Using remote scripting is useful then the category/subcategory combinations are too to send to the numerous as browser Ascript objects. Any number of methods could is defined in this servlet and called similarly from the client.

The subcategories are returned to the client in the format "Index,value;index,value ..." Ideally, this kind of information should is passed using XML, but in order to make this scheme as Cross-browser Friendl Y as possible, the XML is isn't the right choice. If the application environment is confined to Internet Explorer 5 browsers, then XML would was a very elegant to pass I nformation with remote scripting.

In order to make the servlet architecture as extensible as possible, a abstract class that extends HttpServlet is Writte N to dispatch the method invocation generically and package the return value in a way the remote scripting Client-side cod E is built to handle. The HTTP get made by MSRs and JSRs looks like the code in Listing 4.

Because the URL are unique enough to allow the servlet to distinguish between the two different client-side Single abstract servlet class is created that dynamically handles both methods. To show a bit of the details of the two Client-side remote scripting methods work internally; Listing 5 shows the format that's Microsoft client-side remote scripting piece is expecting as the response Est.

At a glance it would appear that XML are being used behind the scenes, but note this value of The Return_value element is not double-quoted and therefore does not follow the XML specification. We ' ll just shake our heads in that apparent oversight and move on. The VERSION of the method element are ignored by the Client-side code, but it's left in just to keep con Sistent with the "return values" from Microsoft's server-side implementation in ASP. The value of the Return_value element is url-encoded. This is unescaped the Client-side framework automatically (note spaces replaced by "%20" rather "+," as is how the JavaScript unescape function requires). The Client-side JavaScript just uses text functions to find the necessary information in the response and builds the ' call Object "Accordingly, which is then returned from Rsexecute to the calling code.

The servlet similarly builds the response to JSRS calls in the format that it expects. The return value was shown in Listing 6.

The heart of the method invocation occurs by Doget method of Remotescriptingservlet (a subclass of HttpServlet). This is the relevant part of Doget:
Listing 7. Doget
String method; int pcount = 0; Callbackname = Request.getparameter ("C"); if (callbackname!= null) {//client is jsrs-it passes a ' C ' parameter ClientType = JSRs; method = Request.getparameter ("F"); JSRs doesn ' t tell us and many parameters, so count them while (Request.getparameter ("P" + Pcount)!= null) pcount++; else {ClientType = MSRs; method = Request.getparameter ("_method"); Pcount = Integer.parseint (Request.getparameter ("PCO Unt ")); }//... some code omitted, refer to the full code included//Find and invoke the appropriate static method in the Concre Te class Class C = This.getclass (); Method M = C.getmethod (method, Paramspec); returnvalue = (String) m.invoke (null, params);

Refer to the "included code for the" Full Remotescriptingservlet Class ("Listing 8"). The ' C ' parameter the ' is ' present for JSRs, and but not for MSRs. Then the idea are to get a reference to the Class of the servlet being invoked (Rsexample, in this case), get a reference t o The method being invoked (Getsubcategories) based on the number of parameters, and then invoke this method with the APPR Opriate parameters. The parameters to the dispatched methods must match in number with the "call" from "the client, and must all is of type Strin G (internally to this method, the Strings can is converted to other types if necessary). Dispatching to static methods is chosen arbitrarily but it could easily dispatch to instance methods rather class m Ethods by specifying ' this ' as the ' the ' ' to invoke. The entire code above is wrapped inside a try/catch blocks, and any exception thrown'll be gracefully sent back to the CL Ient. MSRs errors are reTurned by setting the "TYPE" of Return_value to error, and specifying the escaped ERROR text as the VALUE of retur N_value. JSRs errors are returned as HTML that executes in the onLoad.

Now what? There are all kinds of interesting things the can be accomplished using remote scripting. Taking advantage of the asynchronous feature of remote scripting and JavaScript window timers, a messaging system could be Built to allow a browser to poll the server for messages, content, or other types of update information.

Issuesbecause of the technologies used in remote scripting, there are limitations on the number of browsers it would work W ith. To use MSRs, JavaScript must communicate with the hidden applets to perform the remote call. The Java Virtual Machine (JVM) is only "scriptable" (such, JavaScript and Java applets can communicate) on a limited nu Mber of browsers, meaning only Netscape and Internet Explorer in Win32 (and possibly on other platforms) can support MSRs. Because all parameters are encoded at the URL for an HTTP GET request, there are a limitation to the size of the parameter S. A modified applet exists that does HTTP POST rather than get to eliminate this limitation. Brent Ashley ' s site has the POST version of the applet available for download.

Scalability issues arise if remote scripting is used for continuous. Depending on a application ' s needs, the frequency of requests can be reduced or even made dynamic such that it polls less Frequently if it receives fewer messages and increases the frequency when larger sets of messages are. Since HTTP get are used for the "method call", the size of the the data sent to the "method" is restricted. The response to a remote method has no explicit size restrictions on size; However, if large amounts of data per request are being passed to or from the "server, this messaging architecture be not a Ppropriate.

The security of the remote scripting methods should is considered. By simply opening the appropriate URL along with it necessary parameters in a Web browser, the remote method is being CAL LED and its results are being sent. It may being necessary to assure, the user is logged into the application before returning any results. There are security restrictions ' does not allow a browser to-use cross-host scripting, so ' the host for the main HTM L page must is the same as the host for the remote scripting servlet.

Firewalls are not a issue for communications because HTTP are used, although in some environments Java applets are blocked By firewalls that would prevent Microsoft's remote scripting from working. HTTPS would also work fine with both client-side methods.

Conclusionremote scripting is a great technique to creating a more desktop-like to feel for Web browser-based. The Remotescriptingservlet base class provided with this article opens the door for server-side Java applications to use T Ricks previously only available to Active Server Page applications.

Read Microsoft ' s documentation on remote scripting. Download Brent Ashley ' s JSRs. Get the details of populatedropdowndownload with this example code (including the Remotescriptingservlet Class). Learn the beauty of Java ' s reflection API. Apache ' s Tomcat is used to test this servlet.

About the Authorerik is the President of Ehatcher Solutions, Inc. He also recently joined Promofuel as their octane Site. Being actively involved in software developer organizations at Tucson, AZ, he has presented on Windows NT security analysi S at the back Office Administrators conference with XML for the Tucson Developer Series. You can reach him at

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: 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.