从Javascript调用的Applet方法

我有一个小程序从特定文件夹上传一些文件并删除它们,但是当我从我的javascript代码调用applet函数时出现问题,当我从init()调用该函数时它工作正常.

我的applet代码:

public class Uploader extends Applet {
   String serverPath;
   String clientPath;
   private JSObject win;
   @Override
   public void init() {
       serverPath = getParameter("serverPath");
       clientPath = getParameter("clientPath");
       try {
           win = JSObject.getWindow(this);
       } catch (JSException e) {
           log.warning("Can't access JSObject object");
       }
       upload(topic,clientPath);
   }
   public void upload(String topic,String clientPath) {
       log.log(Level.SEVERE, "upload functiond");
       DefaultHttpClient client = new DefaultHttpClient();
       MultipartEntity form = new MultipartEntity();
       log.log(Level.SEVERE, "upload functiond2");
       try {
            File directory = new File(clientPath);
            log.log(Level.SEVERE, "upload functiond2.2");
            File[] files = directory.listFiles();
            log.log(Level.SEVERE, "upload functiond2.5");
            int i = 0;
            for (File file : files) {
                log.log(Level.SEVERE, "upload functiond2.6");
                i++;
                form.addPart("file" + String.valueOf(i), new FileBody(file));
                System.out.println("adding file " + String.valueOf(i) + " " + file);
                log.log(Level.SEVERE, "adding file " + String.valueOf(i) + " " + file);
            }
            log.log(Level.SEVERE, "upload functiond3");
            form.addPart("topic", new StringBody(topic, Charset.forName("UTF-8")));
            form.addPart("action", new StringBody(action, Charset.forName("UTF-8")));
            form.addPart("path", new StringBody(serverPath, Charset.forName("UTF-8")));
            HttpPost post = new HttpPost(serverPath);
      ....

这是我的javascript代码:

document.applet.upload(title,"c:\scan");

当我从javascript调用时只打印日志:

log.log(Level.SEVERE, "upload functiond2.2");

请注意,当我从applet的init方法调用时,它工作正常.

我将我的代码包装到PriviligedAction中,但只向前迈出一步并坚持下去

log.log(Level.SEVERE, "upload functiond2.5");

解决方法:

Java和JS的交互使安全性变得复杂. JRE不能信任JS,因此它决定包含代码的整个“操作链”是不可信的.有办法解决它.

代码需要包装在PrivilegedAction中,并使用AccessController methods doPrivileged(..)之一调用.查看AccessController文档的顶部. (在方法上方)查看示例用法.

上一篇:Java Web Start小程序/应用程序中的InvocationTargetException


下一篇:在Android上运行Java Applets