I have a scenario where a form has to be filled in as easily as possible. The values to be filled in in the form, are asked from the user initially and stored in database.
Afterwards, when user clicks on a button, a javascript function is invoked that auto-fills all the fields in the form with values obtained by jsp/servlet.
I want to retrieve the values (that are to be filled in into the form) from database with the help of servlet/jsp…Now there should be some way for the javascript function to fill in this value (that was obtained by the servlet/jsp) into the form…
Is it possible to do such sharing of data/variables between jsp/servlets and javascript functions? The javascript functions will be part of the jsp (that retrieves the value that should be filled in in the form).
If the request is sent synchronously (e.g. a form submit button), then you don’t necessarily need JS for this job. Just let JSP/EL print them immediately as input values based on data which is prepopulated by a servlet. For example, assuming that
${user}is a typical Javabean which is prepared by the servlet:(the
fn:escapeXml()is just to prevent XSS attacks)If the request is sent asynchronously (e.g. using ajax), then you just need to let the servlet return the data in a format which is easily parseable by JS, for example JSON.
which you can then use as follows in the ajax response callback function (where
useris the obtained JSON object):jQuery makes things like this much easier. See also How to use Servlets and Ajax?