javascript和java applet互相调用

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

Java、Java Applet与JavaScript间的通信-JSP教程,Java技巧及代码

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

 

 

文一,javascript和javaapplet互相调用  

一 javascript调用java applet方法

1。对无权限要求的一般方法都可调用,有权限要求的方法,例子1.1,1.2,1.3

applet的方法:

1.1。得到盘符(windows平台)

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。读文件

    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。写文件

  public void testWriteFile(String filename, String str) {
        AccessController.doPrivileged(
                new PrivilegedAction() {
            public Object run() {
                try {
                    //File file = new File(filename);// cannot get filename here
                    File file = new 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脚本

<applet
codebase = "."
code     = "testapplet1.Applet1.class"
   archive="testapplet1.jar, lib1.jar, lib2.jar"        //要签名
name     = "TestApplet"
width    = "400"
height   = "300"
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. 得到java对象,直接在javascript中调用该对象的方法


<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()是applet方法:public MyFTPClientgetMyFTPClient();该方法返回一个MyFTPClient 对象。

二 java applet 调用 javascript, 显示进度条的例子

 

javascript和java <wbr>applet互相调用


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在jre的plugin.jar包内

public class applet1 extends Applet {

public applet1() throws HeadlessException {
   super();
}
public void destroy() { }

public String getAppletInfo() {
   return "This is my default applet created by Eclipse";
}

public void init() { }

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){}
    }   
   }
}

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 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){

        //两种方式都可以
        JSObject.getWindow(applet).eval(handler + "(" + count + "," + total + ")");
        //JSObject.getWindow(applet).call(handler, new Object[]{count});    
    }
   }
}

}

<html>
<head>
<style type="text/css">
   .progressBar {
    font-size: 0;
    width: 0%;
    height: 10px;
    background-color: blue;
    margin-top: 2px;
   }
</style>
   
    <script type="text/javascript">
  

    function showprocess(count, total){
           divprocess.className = "progressBar";
           divprocess.style.width = 100*count/total + "%";
           btn.value = divprocess.style.width;
    }
  
   function test(){

        //调用applet的方法
       applet1.test(2);
   }
  
   function window.onload(){

        //向applet注册事件处理方法
        applet1.registerEventHandler('process', 'showprocess');
   }
    </script>
   
</head>

<body>
<div id='divprocess' name='divprocess' ></div>
    <input type=button id='btn' value='test' onclick='test()' />

    <applet codebase="."
            code="test.calljs.applet1.class"
            name="applet1"
            width="0"
            height="0">  
    </applet>
</body>
</html>

<applet ..... MAYSCRIPT></applet>
de>有人说waMAYSCRIPT一定要加上, 不加也可以
参见 http://java.sun.com/products/plugin/1.3/docs/jsobject.html


文二:Java、JavaApplet与JavaScript间的通信-JSP教程,Java技巧及代码

摘要:本文着重阐述了网页开发中,通过灵活使用从javascript语言中访问java的方法、从javascript中访问javascript小程序的方法与变量,以及在javaapplet小程序中使用javascript等技术,实现这几种网页开发语言的互相补充,以开发更完美的web应用程序。


javascript是用于html环境的开发语言,提供了能够响应web页面事件的脚本,可以完全访问浏览器窗口的各个方面,善于合并html、javaapplet小程序、插入件、服务器方程序和其他web组件,形成完全集成的web应用程序。而java是功能强大的著名开发语言,能够支持web应用程序的开发,用于开发高级web对象,并提供实现嵌入web页面的可执行内容,具有更强的编程功能,可以作为javascript功能的良好补充,只不过这些功能被限制在有限的浏览器窗口区中。
java与javascript可以互相补充,以开发功能更完美的web应用程序。本文归纳了笔者编程中曾使用过的,涉及到有关javascript与java、javaapplet小程序之间互访的问题的一些方法,仅供参考。
一、从javascript中访问java方法
在html脚本中可以用javascript直接调用java中的方法,只需要在调用语句前用“java.lang.”加以表示即可。具体语句用法如下例所示:
java.lang.system.out.println(“hello!”)
但此种方法只适用于netscape navigator,一般不提倡在web应用程序中使用。
二、从javascript中访问java applet小程序中的方法和变量
通过javascript提供的applet对象,javascript代码可以访问java的变量和方法,具体步骤和用法示例如下。需要注意的是,javascript提供的applet对象具有name属性,而没有方法和事件处理器。
步骤:
1) 将要访问的java applet小程序的方法和变量声明为public,且必须在public类中声明;
2) javaapplet小程序要先装入才能访问,尽管applet对象没有定义onload事件,但可以在html文档的〈body〉标志中,指定使用window对象的onload事件处理器;
3) java applet小程序可以用javascript的applet对象来访问。
示例:


“mytest.htm”
<html>
<head>
<script language="javascript">
function accessapplet()
{ settimeout("changetext(i like javascript!)",1000);
settimeout("changetext(i like javascript and java!)",2000);
settimeout("changetext(i like java!)",3000);
settimeout("accessapplet()",4000);
}
function changetext(s)
{
window.document.testtext.settext(s)
//此处调用javaapplet小程序的settext()方法
//注意,小程序的名字必须为〈applet〉标志 name属性所标识
}
</script>
</head>
<body onload="accessapplet()">
//通过调用accessapplet()装入小程序
<applet code="testtext.class" name="testtext" width=450 height=150>
</applet>
</body>
</html>
“testtext.java”
import java.applet.*;
……
public class testtext extends applet
{ ……
public void settext(string s) //settext()必须声明为“public”
{
text=s;
repaint();
}
}

三、在java applet小程序中使用javascript
live connect提供了java与javascript的接口,可以允许在javaapplet小程序中使用javascript。具体步骤如下:
1) 在html脚本中使用〈applet〉标志的mayscript属性,以允许java applet小程序访问脚本;
2) 将netscape. javascript包导入java applet小程序;
3) 在java applet小程序中用jsobject类的getwindow()方法创建javascript窗口的句柄;
4) 在java applet小程序中用jsobject类的getmember( )方法访问javascript对象;
5) 在java applet小程序中用jsobject类的eval_r( )方法调用javascript方法。
示例:



“readform. java”
import netscape.javascript.jsobject;
import netscape.javascript.jsexception; //可允许在小程序中处理异常事件
……
win=jsobject.getwindow(this); // 获取javascript窗口句柄,引用当前文档窗口
doc=(jsobject)win.getmember("document"); // 访问javascript对象
form=(jsobject)doc.getmember("textform");
textfield=(jsobject)form.getmember("textfield");
text=(string) textfield.getmember("value"); //获取文本区的值
……
win.eval_r("alert(\"this alert comes from java!\")");
// 调用javascript的alert()方法
……
“user.htm”
……
<body>
<form name="textform">
<p>enter text and then click display text:
<input type="text" name="textfield" size="20"></p>
</form>
<applet code="readform.class" width=200 height=100 name="readapp" mayscript>
//必须使用mayscript属性标志
</applet>
</body>








你可能感兴趣的:(JavaScript,java,exception,String,File,applet)