js和applet交互的回调处理

java最近漏洞多,不过在跨平台方面,目前发现还是它比较强大。在js和applet交互时,发现几个问题:
1、js调用applet方法是同步的,如果applet处理耗时,页面会出现不动卡死的现象。
2、在applet上使用swing组件时,貌似组件非常偶尔显示不正常。
3、如果使用swing弹出模态窗口,页面非常偶尔下出现卡死。
4、2和3两个问题在IE下出现机会比其它浏览器高。

关于1解决方法在applet使用线程处理,再通过线和回调
关于2页面显示直接使用html,applet只提供封装功能,提供函数给js调用。

解决问题1的参考代码

java

import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JApplet;

import netscape.javascript.JSObject;

public class AppletTest extends JApplet{
	public AppletTest() {
		System.out.println("AppletTest============1");
	}
	public void init() {
		System.out.println("AppletTest============2");
		new Thread(){
			public void run(){
				try{

					while(true){
						Thread.sleep(1000);
						System.out.println("init=======================" + getTime());
					}
					
				}
				catch(Exception e){
					e.printStackTrace();
				}
			}
		}.start();
		String parame = "{\"success\":true,\"info\":\"加载完成\"}";
		System.out.println("加载完成=======================" + getTime());
		runJS("initFinish", parame); //调用客户端js方法的
	}
	
	/**
	 * 
	 * @param json 传入的字符串数据
	 * @param fun 回调的函数
	 */
	public void myMethod(final String json, final String fun){
		AccessController.doPrivileged(new PrivilegedAction<Object>() {
			public Object run() {
				new Thread(){ // 另起线程,避免客户端等待applet返回数据卡死
					public void run(){
						try{
							System.out.println("1Thread=======================" + getTime());
							String parame = "{\"success\":true,\"info\":\"执行完毕\"}";
							runJS(fun, parame); //调用客户端js方法的
						}
						catch(Exception e){
							e.printStackTrace();
						}
					}
				}.start();
				System.out.println("2Thread=======================" + getTime());
				return null;
			}
		});
	}
	
	public void runJS(final String jsFun, final String parame) {
		new Thread(new Runnable() {
			public void run() {
				try {
					String fun = "";
					if(jsFun != null && !jsFun.equals("")){
						fun = jsFun + "(" + parame + ")";
						JSObject.getWindow(AppletTest.this).eval("javascript:" + fun + ";");
					}
				} catch (Throwable e) {
					System.out.println("调用js出错=========" + e.getMessage());
				}
			}
		}).start();
	}
	
	public void destroy() {
		super.destroy();
		System.out.println("================== destroy");
		System.exit(0);
	}
	
	public static String getTime() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(new Date());
	}

}

html

<!DOCTYPE HTML>
<html>
<head>
	<meta charset="UTF-8">
	<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script>
<script>
var getTime = function(formatStr, date){
        formatStr = arguments[0] || "yyyy-MM-dd HH:mm:ss";
        date = arguments[1] || new Date();
        var str = formatStr;  
        var Week = ['日','一','二','三','四','五','六']; 
        str=str.replace(/yyyy|YYYY/,date.getFullYear());  
        str=str.replace(/yy|YY/,(date.getYear() % 100)>9?(date.getYear() % 100).toString():'0' + (date.getYear() % 100));  
        str=str.replace(/MM/,date.getMonth()>9?(date.getMonth() + 1):'0' + (date.getMonth() + 1));  
        str=str.replace(/M/g,date.getMonth());  
        str=str.replace(/w|W/g,Week[date.getDay()]);  
        str=str.replace(/dd|DD/,date.getDate()>9?date.getDate().toString():'0' + date.getDate());  
        str=str.replace(/d|D/g,date.getDate());  
        str=str.replace(/hh|HH/,date.getHours()>9?date.getHours().toString():'0' + date.getHours());  
        str=str.replace(/h|H/g,date.getHours());  
        str=str.replace(/mm/,date.getMinutes()>9?date.getMinutes().toString():'0' + date.getMinutes());  
        str=str.replace(/m/g,date.getMinutes());  
        str=str.replace(/ss|SS/,date.getSeconds()>9?date.getSeconds().toString():'0' + date.getSeconds());  
        str=str.replace(/s|S/g,date.getSeconds());  
        return str;  
}

var appletObj = function(){
	this.myMethod = function(json, fun){
		try{
			this.getInstance().myMethod(json, fun);
			console.log(getTime() + "======myMethod:");
		}
		catch(e){
			console.error(getTime() + "====applet程序挂了,请刷新页面:" + e);
		}
	}

	var tool;
	this.getInstance = function(){
		console.log(getTime() + "======typeof tool:" + (typeof tool));
		console.log(getTime() + "======tool:" + tool);
		if(typeof tool == 'undefined'){
			console.log(getTime() + "======getInstance:");
			tool = $("#tool")[0];
		}
		return tool;
	}
	return this;
}();


$(function(){
	$("#btn").click(function(){
		var parame = {data1:'test1'};
		appletObj.myMethod(JSON.stringify(parame), "resultData");
	});

});

function resultData(jsonObj){
	console.log(getTime() + "========jsonObj:" + JSON.stringify(jsonObj));
	console.log(getTime() + "======btn1Click:" + jsonObj.success);
}

function initFinish(jsonObj){
	console.log(getTime() + "========applet init end:" + jsonObj.info);
}
</script>
</head>
<body>  

<applet id="tool" code="test.AppletTest" java_codebase="./" archive="applet.jar" 	width="0" height="0" >
</applet>


<input type="button" id="btn" value="调用applet" />

</body>
</html>

转载于:https://my.oschina.net/penngo/blog/112513

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值