Recipe3.7.Generating JavaScript on the Fly


Recipe 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.

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. Strutsand the underlying JSP technologyruns 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 template text. The template text is anything that isn't processed as part of the JSP translation. People commonly think of template text as the HTML markup, but it is JavaScript or any other non-JSP processed text. The JSP translator does not care what form the template text takes. Therefore, you can as easily generate text into a JavaScript function as you can into an HTML element.

If you are using JSP documents to generate well-formed XHTML, then dynamic JavaScript template text must be specified using a combination of jsp:text elements and CDATA sections. See Hans Bergsten's ONJava article at http://www.onjava.com/pub/a/onjava/2004/04/21/JSP2part3.html for more details.


The Solution presents a simple scenario. If the model data being accessed require the use of complex JavaScript data structures, such as Arrays, you could use iteration tags such as logic:iterate and c:forEach to populate those structures.

See Also

Recipe 3.8 uses iteration tags to generate client-side JavaScript arrays.



    Jakarta Struts Cookbook
    Jakarta Struts Cookbook
    ISBN: 059600771X
    EAN: 2147483647
    Year: 2005
    Pages: 200

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net