【问题标题】:Connection between Java and Javascript through ZK framework通过ZK框架连接Java和Javascript
【发布时间】:2022-12-17 18:08:52
【问题描述】:

我一直面临着通过 iframe 中的 zk 框架在 java 和 javascript 之间进行通信的问题。 简单来说,我想在当前会话中保存一个字符串并在 javascript 中访问它(甚至覆盖它)。

我的 java 行:

HttpSession session = (HttpSession)(Executions.getCurrent()).getDesktop().getSession().getNativeSession();
session.setAttribute("key","testing");

我的祖尔线:

<iframe id = "change_option" src="select_one_option.html" scrolling="no" width="700px" height="400px" > </iframe>

我在 html 文件中的 javascript 行:

var session= /SESS\w*ID=([^;]+)/i.test(document.cookie) ? RegExp.$1 : false;  //finds the correct session id + desktop name?
session = session.substring(0, session.indexOf('.')); //removes desktop name and keeps just the session id in a string 

//another try
console.log("Saved: " + sessionStorage.getItem("key")); //returns "Saved: null" 

//another try 
var username = '<%= Session["key"] =%>'
console.log ( " Variable is : " + username) //returns  "<%= Session["key"] %"

由于 html 文件很大,我认为最好通过 iframe 来完成,而不是尝试在 zul 文件中重写。非常感谢任何建议。

【问题讨论】:

    标签: javascript java zk zul


    【解决方案1】:

    根据您的全部要求,您可以考虑几种方法。

    #1 位于iframe内部的页面和外部页面可以直接通信,使用window postMessage API: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

    这需要一些设置,但允许位于 iframe 中的页面将事件发布到父页面。该事件有一个数据字段,您可以使用它来传输数据。 父页面可以订阅此类事件,并读取事件数据。

    使用这种方法,您实际上不需要在服务器端向会话写入内容,因为这种通信完全发生在客户端。 如果服务器不关心知道值,这很好。

    #2 从内页保存session中的对象,从外页使用它 您已经在本机会话中设置会话属性:

    HttpSession session = (HttpSession)(Executions.getCurrent()).getDesktop().getSession().getNativeSession();
    session.setAttribute("key","testing");
    

    请注意,会话属性仅在 Java 端。它们不会作为 cookie 自动返回给客户端。 如果您想通过 cookie 处理此问题,您可以在响应中添加具有相同值的 cookie: https://www.zkoss.org/wiki/ZK_Developer%27s_Reference/UI_Patterns/Communication/Inter-Application_Communication#Use_Cookie

    然而,这有点矫枉过正,因为 ZK 是一个通信框架,您已经可以通过多种方式将值传递给外部 zul 页面。

    首先,您可以使用 Clients#evalJavascript 方法在页面上执行任意 JS。

    https://www.zkoss.org/wiki/ZK_Developer's_Reference/UI_Patterns/Useful_Java_Utilities#evalJavaScript

    这样,您只需构建一个包含在服务器端检索到的值的 JS 调用,然后在客户端执行它。应该是这样的:

    String myValue = ... //retrieve your server-side value;
    Clients.evalJavascript("myClientSideFunction('"+myValue+"')"); //executed in an execution of the zul page.
    

    但是您也可以将该值用作客户端属性,将其作为组件值传递,等等。

    您可以做很多任意的事情来将该值传递回客户端,所有这些都有利有弊。 例如,如果您想将该值放回文本框中,只需使用 textbox#setValue 方法即可。这实际上取决于您要实现的目标。

    【讨论】:

      猜你喜欢
      • 2015-05-06
      • 1970-01-01
      • 2017-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多