JavaScript and Java applets call each other

Source: Internet
Author: User
Tags getmessage

Http://blog.sina.com.cn/s/blog_487bc31b0100wvha.html

Communication between Java, Java applets and JavaScript-jsp tutorials, Java tips and code

(http://cnc.sudu.cn/info/html/edu/20071227/52151.html)

Text one, JavaScript and Javaapplet call each other

A JavaScript invoke Java applet method

1. For the general method without permission requirement can be called, the method with permission request, example 1.1,1.2,1.3

The method of the applet:

1.1. Get the letter (Windows platform)

Public String getdisklist () {return
         (String) accesscontroller.doprivileged (
            new Privilegedaction () {
                Public Object Run () {
                    try {
                        file[] root = File.listroots ();
                         String disklist = "";
                        for (int i = 0; i < root.length i++) {
                            if (disklist.length () > 0) {
                                disklist = = ",";
                            }
                            Disklist + = Root[i];
                         }
                         return disklist;
                      } catch (Exception e) {
                         System.out.println ("Exception:" + e.getmessage ());
                         return "~~exception~~";
                     } }});
    }

1.2. Read files

    public class Testreadfile_privilegedaction implements privilegedaction{private String m_filename = null;
        Testreadfile_privilegedaction (String filename) {m_filename = filename;
                Public Object Run () {try {System.out.println (' in Testreadfile ');
                File File = new file (m_filename);
                FileInputStream fis = new FileInputStream (file);
                byte[] buf = new byte[1024];
                Fis.read (BUF);
                Fis.close ();
                FILE = null;
                String str = new String (BUF). Trim ();
                System.out.println ("read:" + str);
            return str;
                catch (Exception e) {System.out.println ("Exception:" + e.getmessage ());
            return "~~exception~~";

    }
        }
    }; public string Testreadfile (string filename) {testreadfile_privilegedaction privilegedaction = new TESTREADFILe_privilegedaction (filename);
    Return (String) accesscontroller.doprivileged (privilegedaction); }

.3. Write a file

  public void Testwritefile (string filename, string str) {
        accesscontroller.doprivileged (
                new Privilegedaction ( {Public
            Object run () {
                try {
                    //file file = new file (filename);//Cannot get filename with
                    file = n EW File ("C:/tmp/t2.txt");
                    FileOutputStream fos = new FileOutputStream (file);
                    Fos.write (Str.getbytes ());
                    Fos.write ("Ddddddddffffffffffffff". GetBytes ());
                    Fos.close ();
                    FILE = null;
                } catch (Exception e) {
                    System.out.println ("Exception:" + e.getmessage ());
                }
                return null;}}
        );

    

JavaScript script

<applet
codebase = "."
Code     = "Testapplet1." Applet1.class "
   archive=" Testapplet1.jar, Lib1.jar, Lib2.jar "        //To sign
name     =" Testapplet "
width    = "the"
height   = "hspace"   = "0"
vspace = "   0"
align    = "Middle"
id = "Testapplet1"
>
</applet>

<script type= "Text/javascript" language= "Javascript" >

function Btnclick ()
{
var ret = testapplet1.testreadfile (' c:/tmp/t1.txt ');
Alert ("Test read:" + ret);
Testapplet1.testwritefile (' K:/java/tmp/t2.txt ', ' Sdafsfsdgffgfgretertsfds ');
Alert ("Test write Done");
ret = Testapplet1.getdisklist ();
Alert ("Get disk list:" + ret);

}

</script>

2. Get Java object, call the object directly in JavaScript method


<script language= "javascript" type= "Text/javascript" >

var f = testapplet1.getmyftpclient ();
F.connect ("127.0.0.1");
F.login ("Jiangyl", "1234");
F.storefile ("/tmmpp.dat", "C:\\tmp\\ftp\\tmp.dat", null);
F.retrievefile ("/tmp.dat", "C:\\tmp\\ftp\\tmp123.dat", null);
F.logout ();

</script>

Getmyftpclient () is the Applet method: Public myftpclientgetmyftpclient (), which returns a Myftpclient object.

Two Java applets invoke JavaScript, showing examples of progress bars


Package Test.calljs;
Import Java.applet.Applet;
Import Java.awt.Color;
Import java.awt.HeadlessException;

Import java.util.Hashtable;

Import Netscape.javascript.JSObject; Netscape.javascript.JSObject in the JRE Plugin.jar package public class Applet1 extends applets {public applet1 () throws ception {super ().} public void Destroy () {} public String Getappletinfo () {return ' This is the My default applet CR
Eated by Eclipse ";

  The public void init () {} is public void Start () {this.setbackground (Color.Blue);
Test (1);

public void Stop () {} private Transeventjs Transeventjs = new Transeventjs (this);
  
    public class process implements runnable{private Transeventjs Transeventjs = null;
   Public process (Transeventjs transeventjs) {This.transeventjs = Transeventjs;
       public void Run () {for (int i=1; i<=100; i++) {this.transEventjs.process (i, 100); Try{thread.sleep (100);} catch (Exception e) {}}} is public void test (int repCNT) {System.out.println (repcnt);
New Thread (New process (Transeventjs)). Start (); public void Registereventhandler (string event, string handler) {Transeventjs.geteventhandlers (). Put (event, Handler)
;  
public interface transevent{//start//stop ... public void process (int count, int total);
  
   public class Transeventjs implements transevent{private applet = null;
   Public Transeventjs (Applet applet) {this.applet = applet;
  
   Private hashtable<string, string> eventhandlers = new hashtable<string, string> ();
   Public hashtable<string, String> geteventhandlers () {return eventhandlers;
    public void process (int count, int total) {String handler = Eventhandlers.get ("process"); if (handler!= null) {//Two methods can be Jsobject.getwindow (applet). Eval (handler + "(" + Count + "," + Total + ")
        );    
    Jsobject.getwindow (applet). Call (Handler, new Object[]{count}); }
   }
}

}

First, accessing Java methods from JavaScript
You can use JavaScript directly in HTML scripts to invoke methods in Java, simply by using "Java.lang." Before calling the statement. can be expressed. The specific statement usage is shown in the following example:
Java.lang.system.out.println ("hello!")
However, this method applies only to Netscape Navigator and is not generally advocated for use in Web applications.
Ii. accessing methods and variables in Java applet applets from JavaScript
JavaScript code provides access to Java variables and methods through JavaScript-provided applet objects, such as the steps and usages below. It is important to note that the applet object provided by JavaScript has the Name property and no methods and event handlers.
Steps:
1 The method and variable of the Java applets applet to be accessed are declared public and must be declared in the public class;
2) Javaapplet applet to be loaded before access, although the Applet object does not define onload event, but you can in the HTML document 〈body〉 flag, specify the OnLoad event handler to use the Window object;
3 Java applet applets can be accessed using JavaScript applet objects.
Example:


"Mytest.htm"

Third, use JavaScript in Java applet applets
Live Connect provides Java and JavaScript interfaces that allow JavaScript to be used in Javaapplet applets. The specific steps are as follows:
1 Use the Mayscript attribute of the 〈applet〉 flag in the HTML script to allow Java applet applets to access the script;
2) will Netscape. JavaScript packages import Java applet applets;
3 Create a handle to the JavaScript window using the GetWindow () method of the Jsobject class in the Java applets applet;
4) accessing JavaScript objects in Java applet applets using the GetMember () method of the Jsobject class;
5 invoke the JavaScript method with the Eval_r () method of the Jsobject class in the Java applets applet.
Example:



"Readform. Java "
import netscape.javascript.jsobject
import netscape.javascript.jsexception;//To allow handling of exception events in applets ...
... Win=jsobject.getwindow (this);//Get the JavaScript window handle, referencing the current document window
doc= (jsobject) win.getmember ("document"); Access JavaScript Object
form= (jsobject) doc.getmember ("Textform");
textfield= (Jsobject) form.getmember ("TextField ");
text= (String) textfield.getmember (" value "); Gets the value
of the text area ... Win.eval_r ("alert (\" This alert comes from java!\));
//Invoke JavaScript's alert () method
...
" User.htm "
...
<body>
<form name= "Textform" >
<p>enter Text and then click Display text:
<input Type= "text" name= "TextField" size= "></p>
</form> <applet code=" Readform.class "
width=200 height=100 name= "Readapp" mayscript>
//must use MAYSCRIPT attribute flag
</applet>
</body >








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.