Communication between Java and JavaScript

Source: Internet
Author: User

1. The internal ideas of the chat demonstration program, together with this article, are all my own. All chat programs I have seen are not completely based on Java or HTML. My method is a good balance between the two methods.

2. After reading a large number of articles on the Netscape developer site, I collected technical information for communication between Java and JavaScript.

3. When I was reading Danny Goodman's article for the first time (the Javascript apostle on the Netscape site), I came across the term "Faceless applet )". So out of trust in Danny, I used this very short term.

Give up

1. The technology discussed in this article has been tested on Windows 2000 Professional machines using Internet Explorer 5.0 and Netscape Navigator 4.7. In the best works I know, these technologies should run on any browser version above 4.0, but I cannot guarantee that I do this, because I don't have time to use these versions to test it.

2. Because Javascript is the only language supported by both major browsers, all script code uses this language. I previously used an available commercial plug-in on the http://www.ncompasslabs.com that allowed Netscape Navigator to support VBScript, but when I went to their site to verify this information, this product is not listed.

Introduction

I have been working in modern COM for two years. Now I am the technical leader of our e-commerce product team. I understand the importance of good interface design and program execution in different environments, such as Visual C ++, Visual Basic, and scripts. The ability to design an interface-based program has always been established in my mind, and as a software engineer I 've tried to apply it to everything I'm dealing.

In the past year, when ASP + scripts are to be used as the binder for these objects, experience tells us that diligence: All business logic should be compressed into COM objects. Designing and developing typical infrastructure and business objects requires a higher level of technical equipment, which is used to compare what actually requires the use of the same thing. The preferred environment for developing these objects (at least in my team) is Visual C ++/ATL/STL. Microsoft also encouraged Visual Basic to become the development environment available for these objects.

These objects are often referred to as "unknown" because they implement a lot of logic, except for the user interface. Its presentation level (Presentation tier) is not a sufficient customer or an insufficient customer (this customer has the logic to express and aggregate information from the end user ). Then such a customer uses this information to do meaningful things by using unknown objects. The whole idea is that when business objects do not change frequently, their performance levels will be representative and require customization by many customers. Changes to performance levels can also be achieved through the use of less experienced programs.

Apply the same principles to the browser environment. When using a scripting language to process performance, in the "unknown" binary module, compressing the logic of highly developed clients seems logical. On Windows, the options of these modules are Java Applet and ActiveX Control/server. The focus of this article is to use a Java applet to accomplish this goal, because the applet is independent of the browser, platform, and processor (for most cases ).

Brief history of the Applet

In 1995, Sun Microsystems introduced a Java Applet in the horn sound. The applet immediately wins the favor of the web world, because they increase the ability to dynamically display web content in browsers in the original static html world.

In the first days, Java Applet was used as the best way to add dynamic content to webpages. Microsoft initially tried to use their ActiveX Control Technology Against the Java Applet provided by Sun, but there are two main problems with using controls inside the webpage:

● The binary module is specified by the processor, so it is not suitable for running as part of a webpage. One major reason why the World Wide Web is so successful is the fact that most web pages written using W3C standard HTML are unknown to browsers and processors. ActiveX controls do not match this example.

● Security is a big problem because the control writer has sufficient rights to access resources on the customer's machine. The named control allows anyone to view the webpage and intelligently decide whether to download a specific control from his/her machine, however, all the tasks he performed were accidentally clicking a button (or happily ignoring it), leaving a vulnerable client, which is in line with the intention of the malicious control writer.

When dynamic HTML was finally formed, things completely changed. Document Object Model (Document Object Model) is a component that can be designed. They expose webpage elements using their own attributes and methods. Even though the Internet Explorer and Netscape Navigator browsers execute Dynamic HTML in many different ways, it is a great success to use the script code to programmatically change the fundamental theme of displaying the page content itself. The applet suddenly began to look old and rough. W3C's recognition of Dynamic HTML is ultimately highly developed, and the tone of the new category of dynamic web pages is adjusted.

Using Java Applet in a browser has the following advantages:

● Applet (for most applets) can work on multiple browsers, platforms, and processors.

● Java is a typical and powerful conceptual language.

● JDK has many typical useful classes created only in High-level class libraries.

● Security has been conceived in technology. The applet can only run in the box by default. To break the limitations of the box, the applet must have been named.

● The applet can send back user information, upload/download files, and get in touch with the Web server. A signed applet can be connected to any server, not just a host.

● The "View Source File" option does not allow you to view the applet code, thus protecting intellectual property rights.

● The. Class file in Java is very small, and the result is that the download speed is very fast.

Disadvantages of using Java Apple:

● In a browser conversation, the download applet is displayed either immediately after the webpage uses them or after the webpage is refreshed. The applet is not resident on the client in the browser conversation. In fact, this can be considered as an advantage in most cases.

● Applet initialization takes a long time.

● Because the java. Class file is a byte code interpreted by the Java Virtual Machine (JVM), the applet runs slowly than the local code.

● An applet is only part of the real state of the browser, and it does not appear seamlessly in the webpage content. Cascading Style Sheet (CSS) does not directly affect the rectangular area occupied by the applet.

● Netscape Navigator 4.x has 10 active applets. I do not know that Internet Explorer 4.0 + has any such restriction.

Quick review of using Java applets

Java applets is included into an HTML webpage by using the applet tag. Section 4.01 of the HTML 13.4 documentation on the W3C site details this tag. It also mentions consent to <Object>, rather than using this mark.

An HTML webpage that contains the applet is shown as follows:

<HTML>
<Head>
<Title> calculator </title>
</Head>
<Body>
<APPLET id = "Calculator" width = "300" Height = "500" code = "Calculator. Class" codebase = ".">
<Param name = "initialmode" value = "normal">
</APPLET>
</Body>
</Html>
The attributes used in the preceding example are described as follows:

ID
The identifier of the applet instance. The client script code knows the applet using this ID.

Width
This attribute specifies the initial width of the applet display field (excluding the window or dialog box created by the applet ). Even if I have successfully used the browser mentioned in the "discard" section for width 0, we recommend that you use value 1 as the minimum possible width.

Height
This attribute specifies the initial height of the applet display field (excluding the window or dialog box created by the applet ). Like using the width attribute, we recommend that you use value 1 as the minimum possible width.

Code
This attribute specifies the name of any class of files (including the applet subclass compiled by the applet or the class path that can be obtained, including the class file itself). It will be explained when it comes to the codebase of the applet.

Codebase
This attribute specifies the basic URI of the applet. If this attribute is not specified, the latest document is the same basic URI by default.

Only the code, width, and height attributes are required.

The param tag contains a pair of name values, which allow the applet to install itself during the first runtime.

The preceding applet calls the JavaScript function of a method as follows, which is very simple:

<Script language = JavaScript>
Function setcalculatormode (Mode)
{
Document. Calculator. setcalculatormode (mode );
// Alternative way to reference the applet.
// Document. Applets [0]. setcalculatormode (mode );
}
</SCRIPT>
Labor Division

In the introduction section of this article, I suggest that when JavaScript code is used to process the representation, a highly developed browser is compressing the content into an unknown Java applets. This method requires two-way communication between Java and JavaScript. The following sections will look at available options.

Accessing the members and functions exposed by Java Applet through JavaScript code is straightforward, as described in the setcalculatormode () function in the previous section. The Applet in the document is queried either by using its ID/name or by using the index collected by the applet.

For example:

Document. Calculator. setcalculatormode (mode); // or document. Applets [0]. setcalculatormode (mode );

Use the Netscape. Javascript. jsobject class and the Netscape. Javascript. jsexception class to complete the communication between other directions (Java to Javascript. To locate where these classes are located, I am searching for all files containing the string "jsobject" on my hard drive. To my surprise, these files are widely used in many different programs, including libraries that are part of the Visual InterDev project.

If Netscape Navigator 4.0 + is installed on your machine, these. class files are available in the java40.jar file under the <navigator installation directory> \ communicator \ Program \ Java \ Classes directory.

I am also searching for these. class files in four different. ZIP files under the <Windows installation directory> \ Java \ packagesdirectory. These. ZIP files are obviously installed on Microsoft products because they contain many com. Ms packages. Their purpose is that these two classes are available to any browser. You can set your classpath environment variable to any of the above paths. You can use a program like winzipto extract these files from the .jar).zip file to your applet directory.

Jsobject class

A brief description of the referenced jsobject class member function is used to better understand the purpose of the class.

Public static jsobject getwindow (applet)

This static method returns a jsobject for the given applet window. Example: jsobject mainwindow = jsobject. getwindow (this );

Public object call (string methodname, object ARGs [])

This function calls a JavaScript method from the Java applet. For example:

Jsobject mainwindow = jsobject. getwindow (this );
String arguments [] = {"90", "2"}; // {"percent complete", "time remaining "}
Mainwindow. Call ("updateprogressindicator", arguments );
Public object eval (string S)

This method is used to evaluate the value of a javascript expression. The expression is a string of the JavaScript source code to be obtained in the context of this object. For example:

Jsobject mainwindow = jsobject. getwindow (this );
Jsobject username = mainwin. eval ("document. userinfoform. username ");
Public object getmember (string name)
This method retrieves an index member of a JavaScript Object, which is equivalent to this. Name of the JavaScript Object. :
Jsobject mainwindow = jsobject. getwindow (this );
Jsobject documentpage = (jsobject) mainwindow. getmember ("document ");
Jsobject userinfoform = (jsobject) documentpage. getmember ("userinfoform ");
Jsobject username = (jsobject) userinfoform. getmember ("username ");
Public object getslot (INT index)
This method retrieves an index member of a JavaScript Object, which is equivalent to this [Index] of a JavaScript Object. For example:
Jsobject mainwindow = jsobject. getwindow (this );
Jsobject documentpage = (jsobject) mainwindow. getmember ("document ");
Jsobject applets = (jsobject) documentpage. getmember ("applets ");
Object theapplet = applets. getslot (INDEX );
Public void removemember (string name)
This method deletes a specified member of a JavaScript Object.
Public void setmember (string name, object value)
This method sets a specified member of a JavaScript Object. It is equivalent to this. Name = value of a JavaScript Object. For example:
Jsobject mainwin = jsobject. getwindow (this );
Jsobject documentpage = (jsobject) mainwin. getmember ("document ");
Jsobject userinfoform = (jsobject) documentpage. getmember ("userinfoform ");
Jsobject username = (jsobject) userinfoform. getmember ("username ");
Username. setmember ("value", "Jeremiah S. talkar ");
Public void setslot (INT index, object value)
This method sets the index member of a JavaScript Object. It is equivalent to this [Index] = value of a JavaScript Object.
Public String tostring ()

This method converts jsobject into a string.

The above example is clear. The common methods of the jsobject class are unrestricted when attempting to call JavaScript Functions in Java applet. They can also enable an applet to directly Process Document Object Model Elements.

Complete documents of these classes can be obtained at http://developer.netscape.com/docs/manuals/communicator/jsref/pkg.htm.

The document also explains how to process data types between Java and JavaScript.

Significance of mayscript attributes

Even if the applet uses jsobject to call JavaScript Functions or directly accesses the Document Object Model, the jsobject method fails if the applet tag is not included in the mayscript attribute. This allows web designers to determine whether an applet can call JavaScript.

Communication between unknown applets

When an unknown Java applet is used on a webpage but can be used again, it is possible that one applet needs to communicate directly with another applet. Such a call can also communicate through a media JavaScript function, but it is always better to be familiar with all available options.

The appletcontext interface of the Java. Applet package imposes an access restriction on the applet context. For example, if an applet is inserted into the browser, another applet on the webpage is also on the same webpage.

For example, an HTML page contains two applets:

HTML>
<Head>
<Title> communication between applets </title>
</Head>
<Body>
<APPLET code = "circlearea. Class" name = "circlearea" width = 1 Height = 1>
</APPLET>
<APPLET code = "picalculator. Class" name = "picalculator" width = 1 Height = 1>
</APPLET>
...
</Body>
</Html>

The following code indicates the appletcontext object usage:

Appletcontext context = getappletcontext ();
Picalculator piapplet = (picalculator) Context. getapplet ("picalculator ");
Piapplet. getvalueofpi ();

Another option is to use the appletcontext: getapplets () method, which returns an enumeration type for all the applets in the access document. Even if the applet communication is part of the standard Java Applet API, it will not be supported in all browsers that allow Java. The core code of other applets is also uncertain. The best way is to use JavaScript Functions to handle such communication.

Java iunknown: QueryInterface class object is the root of the class hierarchy. Each class has a superclass. All objects, including arrays, implement this class method. The object: getclass () method returns the "class" of functions that are useful for exploring Java class details ". Although I have explained in detail in the previous part of this article, I still want to point out that the getinterfaces () method enables the discovery of dynamic interfaces to be implemented through a Java class.

I have not tried to call the getclass () method in Javascript, so I cannot comment on its feasibility. However, with the basic type of Applet, this function can easily make it available to script code.

Install sample files

The Demo code of this article has been compressed in the java2javascript.zip file. The example file demonstrates a chat program that has simply sent messages to the client. The user adds a message to the chat on different machines and then broadcasts it to all the participants.

The file that makes up the example is:

Isession. Java
Define the source file of the isession Interface

Isession. Class
Java byte code of the isession Interface

Chatclient. Java
Demonstrate the source file of the chatclient Applet

Chatclient. Class
Java byte code of the chatclient Applet Class

Compilechatclient. bat
Batch files of simple Java source files

Testchatclient.htm
Supports chatclient applet HTML files

Jsobject. Class
Byte Code of the jsobject class

Jsexception. Class
Byte Code of the jsexception class

To install and run the sample program, follow these steps:

● Decompress java2javascript.zip on a machine running the personal Web server or Internet Information Server to your selected directory.

● Ensure that the jsobject and jsexception class files in the Netscape \ JavaScript subdirectory under the installation directory are available.

● Right-click the installation directory and select "properties ".

● Click the "webpage sharing" tab and select the "share this folder" option. In the displayed dialog box, accept the default value "virtual directory ".

● Finally, start Internet Explorer 4.0 + or Netscape Navigator 4.0 +, and enter the URL http: // <machine Name>/<virtual directory>/testchatclient.htm.

Enter some text in the input box, and then click the "send" button to view the message in the chat window.

Sample Code

Chat programs are popular cooperation mechanisms on Web pages. I have seen two types of chat programs:

● One is a Java applet that manages the communication between the user interface and the server.

● The other is to automatically refresh the page every few seconds to display the HTML pages of all new messages after the last refresh.

Recently, I have to implement product quality for chat programs of E-commerce products. After many considerations, I decided to use a hybrid method. First of all, the most important Java applet is an unknown applet that executes the isession interface.

Public interface isession
{
// Type is used to differentiate the actual message string
// And can be set to 'text', hyperlink 'etc.

// Shocould be invoked first to indicate to the server that
// New person has joined the chat.
Public int beginsession (string strauthor, string stroptions, string strtype, string strmessage );

// Shocould be invoked when the author wants to exit the chat.
Public int endsession (string strauthor, string strtype, string strmessage );

// Used to send the chat messages.
Public int sendmessage (string strauthor, string strtype, string strmessage );
}
I have slightly modified this interface in the chat program product version, including the author parameters of endsession () and sendmessage. This is because my demo program uses an applet to send chat messages between two different chatbots.

The chatclient. Java file is the actual execution file of the isession interface. If they are executed, the browser calls the init (), start (), and stop () functions (). The jsobject In the description document window is obtained after the init () method is executed.

// Get the Javascript window that will have the varous scripts that this applet will call.
M_jscriptwin = jsobject. getwindow (this );

Because Java Applet calls two different JavaScript Functions, I decided to enable Web developers to specify the names of these functions like applet parameters until the default value is provided for the same applet.

M_strmessagehandler = getparameter ("messagehandler ");
M_strerrorhandler = getparameter ("errorhandler ");
Beginsession () and endsession () are virtual execution functions that only execute sendmessage.
Sendmessage () calls the JavaScript function name specified in the m_strmessagehandler member variable. The default value is "handlesessionmessage ". The related code is as follows:
If (m_jscriptwin! = NULL)
{
String arguments [] = {strauthor, strtype, strmessage };
M_jscriptwin.call (m_strmessagehandler, arguments );
}
Handlesessionerror () calls a JavaScript function name specified in the m_strerrorhandler member variable. The default value is "handlesessionerror ".
Testchatclient.htm. The applet uses the <APPLET> flag to include it in the webpage.
<APPLET id = "chatapplet" width = "1" Height = "1" code = "chatclient. Class" codebase = "." viewastext mayscript>
<Param name = "messagehandler" value = "handlesessionmessageex">
<Param name = "errorhandler" value = "handlesessionerrorex">
</APPLET>
The parameter specifies the names of the two JavaScript Functions called by the applet. I only show that the name except the default value shows how flexible this method is. The two forms on the webpage simulate two people chatting with each other. The related HTML is also easy to understand.
In fact, the message itself is displayed on <div>. In Internet Explorer, I use the table object model to display each message in a single row. Therefore, chatmessagestable is defined on <div>.
Finally, the handlesessionmessagesex () JavaScript function handles all the performance aspects. In Internet Explorer, a new row is added to the chatmessagestable table after each message is sent. A scroll bar is displayed if needed. In Netscape Navigator, I append a new message to the messages variable and use the latter to update chatmessages <div>. Since the scroll bar is not automatically displayed on Netscape <div> (a real layer), I will display the last received message on the top. I have found an article on how to support layer scroll bars in navigator, but it has nothing to do with this example.
Last thought
This article attempts to introduce some (elegant) browser logic technologies. As I mentioned earlier in this article, jsobject is widely used in many programs, including Microsoft. Similarly, you need to consider your personal environment to determine whether the technology described here is available.
As for the example programs attached to this article, I think that the introduction of enabling JavaScript/DHTML to implement chat enables this code to be maintained through entry level/low-level programmers. It is also easy to customize the user interface using DHTML/JavaScript. In addition, it allows more powerful performance techniques that seem to be consistent with the remaining web content.
In the product version of this program, I added support for switching and opening hyperconnections on the participant machine and dynamically selecting the message color using the stacked style sheet.
Any feedback

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.