Skip to Main Content
Jakarta Struts Cookbook
book

Jakarta Struts Cookbook

by Bill Siggelkow
February 2005
Intermediate to advanced content levelIntermediate to advanced
528 pages
12h 53m
English
O'Reilly Media, Inc.
Content preview from Jakarta Struts Cookbook

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming Jakarta Struts

Programming Jakarta Struts

Chuck Cavaness
Beginning Spring Framework 2

Beginning Spring Framework 2

Bruce Snyder, Sing Li, Anne Horton, Thomas Van de Velde, Naveen Balani, Christian Dupuis
Java Cookbook

Java Cookbook

Ian F. Darwin
Struts 2 in Action

Struts 2 in Action

J. Scott Stanlick, Chad Michael Davis, Donald J. Brown

Publisher Resources

ISBN: 059600771XSupplemental ContentErrata Page