Access Java / Servlet / JSP / JSTL / EL variables in JavaScript -


i have form in jsp. have populate based on request object (from servlet). how use java script accessing request object attributes or if can suggest me other better way populate form dynamically?

you need realize java/jsp merely html/css/js code producer. need let jsp print java variable if javascript variable , generated html/js code output syntactically valid.

provided java variable available in el scope ${foo}, here several examples how print it:

<script>var foo = '${foo}';</script> 
<script>somefunction('${foo}');</script> 
<div onclick="somefunction('${foo}')">...</div> 

imagine java variable has value "bar", jsp generate html can verify rightclick, view source in webbrowser:

<script>var foo = 'bar';</script> 
<script>somefunction('bar');</script> 
<div onclick="somefunction('bar')">...</div> 

do note singlequotes mandatory in order represent string typed variable in js. if have used var foo = ${foo}; instead, print var foo = bar;, may end in "bar undefined" errors in when attempt access further down in js code (you can see js errors in js console of browser's web developer toolset can open pressing f12 in chrome/firefox23+/ie9+). note if variable represents number or boolean, doesn't need quoted, work fine.

if variable happens originate user-controlled input, keep in mind take account xss attack holes , js escaping. near bottom of our el wiki page can find example how create custom el function escapes java variable safe usage in js.

if variable bit more complex, e.g. java bean, or list thereof, or map, can use 1 of many available json libraries convert java object json string. here's example assuming gson.

string someobjectasjson = new gson().tojson(someobject); 

note way don't need print quoted string anymore.

<script>var foo = ${someobjectasjson};</script> 

see also:


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -