JavaRanch Home    
 
This page:         last edited 20 July 2012         What's Changed?         Edit

Can I mix JSP with JavaScript?   

No, not directly.

The JSP executes on the server, long before the page gets sent to the browser where the JavaScript can be evaluated.

Please read this article to understand how JSP operates. You should not write one more line of JSP code until you understand what JSP is, and what JSP is not!

What you can do is to use JSP to dynamically create JavaScript markup to be sent to the browser. But remember, the server doesn't know anything about JavaScript, all you can do is to create the JavaScript code that will be executed later, after the page has been loaded into the browser.

For example, let's say you have a scoped variable named "fred" that contains the string "Hi there!", and you want to make this a JavaScript variable. The following markup would accomplish that:

 var jsString = '${fred}';

Note that the JSP EL expression is simply evaluated in place. What is sent to the browser is:

 var jsString = 'Hi there!';

The variable "fred" is not sent to the browser, and JavaScript knows nothing about it.

P.S. If you want to dynamically include page fragments as the result of a client action, then you'll need to use Ajax.

P.P.S. Do not be fooled by the name JavaScript — it might lead you to think that JavaScript has something to do with Java, but it does not. Aside from sharing some syntactical elements, they have nothing whatsoever to do with each other.



JspFaq

JavaRanchContact us — Copyright © 1998-2014 Paul Wheaton