我有一个内部网站点的Java小程序,需要访问客户端PC上的文件系统(特别是LAN共享)。这个小程序的功能类似于:
JSObject win;
public void init() {
win=(JSObject) JSObject.getWindow(this);
win.call("appletMsg", new Object[] {"<b>Applet Loaded</b>", "win"});
}
public void saveFile(String filepath, String filename) {
File theDir = new File(filepath);
try {
if (theDir.exists()) { // This throws exception
win.call("appletMsg", new Object[] {"Directory Exists", "win"});
}
else {
win.call("appletMsg", new Object[] {"Creating Directory...", "msg"});
if (theDir.mkdir()) {
win.call("appletMsg", new Object[] {"Directory Created", "win"});
}
else win.call("appletMsg", new Object[] {"Directory Creation Failed!", "fail"});
}
}
catch (Exception e) { // This exception is caught
win.call("appletMsg", new Object[] {"Error Reading Directory!", "fail"});
win.call("appletMsg", new Object[] {filepath, "fail"});
}
// More code for working with files, error happens above this
}
applet背后的Javascript
// call applet method
function save() {
document.myApplet.saveFile('\\\\LOCATION\\DIR\\DIR\\', 'test.txt');
}
// output responses from applet to div
function appletMsg(response, type) {
document.getElementById('output').innerHTML+='<br><span class='+type+'>'+response+'</span>';
}
故障排除/思想:
答案 0 :(得分:2)
为了能够从JavaScript调用您的applet函数,您必须使用访问控制器。 请参阅documentation。
所以试试:
public void saveFile(String filepath, String filename) {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
File theDir = new File(filepath);
try {
if (theDir.exists()) { // This throws exception
win.call("appletMsg", new Object[] { "Directory Exists", "win" });
} else {
win.call("appletMsg", new Object[] { "Creating Directory...", "msg" });
if (theDir.mkdir()) {
win.call("appletMsg", new Object[] { "Directory Created", "win" });
} else
win.call("appletMsg", new Object[] { "Directory Creation Failed!", "fail" });
}
} catch (Exception e) { // This exception is caught
win.call("appletMsg", new Object[] { "Error Reading Directory!", "fail" });
win.call("appletMsg", new Object[] { filepath, "fail" });
}
// More code for working with files, error happens above this
}
});
}
即使使用自签名证书也可以,您只需获得安全警告。
始终记住使特权代码部分尽可能小。