【问题标题】:Pass values from Servlet to an onload JavaScript function in a JSP将值从 Servlet 传递到 JSP 中的 onload JavaScript 函数
【发布时间】:2012-04-17 12:48:08
【问题描述】:

我在我的 Servlet 中使用以下代码来设置属性 confirmMsg

req.setAttribute("confirmMsg", "Update Values");

这个我转发给 JSP

RequestDispatcher rd = req.getRequestDispatcher("displayDetails.jsp");
rd.forward(req, resp);

在我的 JSP 中,我需要在页面加载时显示消息。

<body onload = "showConfirmMsg();">

// .....

</body>

在下面的函数中我应该怎么做才能显示消息onload本身?

function showConfirmMsg() {

// Code to show the alert box onload

}

【问题讨论】:

    标签: javascript jsp servlets onload


    【解决方案1】:

    使用 jQuery,您可以执行以下操作:

    <script>
    $(function() {
        var msg = "${confirmMsg}";
        // do something with your message :)
    });
    </script>
    

    &lt;body onload=""&gt; 不是很干净 :)

    【讨论】:

    • 现在还推荐这种方案吗?
    【解决方案2】:

    只需让 JSP/EL 相应地打印 JS 代码,以便浏览器检索有效的 HTML/JS 代码。

    例如

    <body onload="showConfirmMsg('${confirmMsg}');">
    

    function showConfirmMsg(confirmMsg) {
        // ...
    }
    

    如果您不能保证 ${confirmMsg} 不包含 JS 特殊字符,例如 '、换行符等,那么您需要预先通过例如 Apache Commons Lang StringEscapeUtils#escapeJavaScript() 对其进行转义。

    【讨论】:

      【解决方案3】:

      加载时不需要调用函数,而是使用 JSP 脚本。

      <body>
      <%=request.getAttribute("confirmMsg")%>
      </body>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-25
        • 2012-05-03
        • 1970-01-01
        • 1970-01-01
        • 2014-06-22
        • 1970-01-01
        相关资源
        最近更新 更多