3.7. Generating JavaScript on the Fly
Problem
You want to generate JavaScript dynamically using data retrieved from your application's Model.
Solution
Use the Struts tags to render data within the JavaScript code just as you would within HTML:
<script language="JavaScript">
function showMessage( ) {
alert( "Hello, <bean:write name='myForm' property='name'/>!" );
}
</script>Discussion
The Solution above generates a JavaScript function that pops up a
message box with the text "Hello,
name!" The value for
name is generated using the
bean:write tag.
The Solution shows how the Struts tags can be used to create
JavaScript just as easily as they create HTML.
Tip
JSTL can be used in the same manner.
While this solution seems obvious, it is surprising how many times this question comes up. Often the question is posed as, "How do I call a JavaScript function in HTML from Struts?" Technically, you can't call a JavaScript function on an HTML page from Struts. Struts—and the underlying JSP technology—runs on the server-side. JavaScript, in contrast, is processed by the browser on the client-side. However, with the dynamic generation capabilities of Struts as shown in the Solution, you can approximate this behavior.
Another important concept that this recipe hinges on is the JSP
translation process. A JSP page is composed of JSP declarations,
standard JSP tags (such as jsp:useBean), custom JSP tags (such as the Struts and JSTP tags), runtime expressions, and scriptlets. Everything else in the page is ...