2012-04-17 85 views
0

我用我的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 

} 

回答

3

使用jQuery,你可以這樣做:

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

<body onload="">不是很乾淨:)

+0

這種情況現在仍然推薦嗎? – Perdomoff 2016-02-11 20:28:25

0

讓JSP/EL相應地打印JS代碼,以便瀏覽器檢索有效的HTML/JS代碼。

E.g.

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

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

如果你不能保證${confirmMsg}不包含像',換行,JS-特殊字符等等,那麼你需要事先通過例如Apache的百科全書逃跑呢Lang StringEscapeUtils#escapeJavaScript()

0

無需調用加載的功能,而不是使用JSP scriplet。

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