I am new to web development. I have an external JavaScript file which has a function to show a prompt with error details. I need to pass the error message to the function. I
You need to understand that a servlet runs in the webserver, not in the webbrowser and that JS runs in the webbrowser, not in the webserver. The normal practice is to let the servlet forward the request to a JSP file which in turns produces HTML/CSS/JS code which get sent to the webbrowser by the webserver. Ultimately, all that HTML/CSS/JS code get executed in the webbrowser.
To achieve your (somewhat strange, tbh) functional requirement, just let the forwarded JSP conditionally render the particular script call. For example as follows with JSTL
, assuming that you've collected and set the errors as ${errors}
in JSON array format:
Or let JSP assign it as a JS variable and let JS handle it further. Something like:
As to the requirement being strange, if you're forced to use JS to display messages, that can only mean that you're using an alert()
or something. This is very 90's and not user friendly. Just let JSP produce the HTML accordingly that they're put next to the input fields, or in a list on top of the form. Our servlets wiki page has a hello world example which does exactly like that.