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
It is not possible to call a java script function from a servlet. Rather, you can print javascript code using
response.getOutputStream().println("[javascript code]");
into the browser and then the javascript function will be executed in the browser.
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 <c:if>
, assuming that you've collected and set the errors as ${errors}
in JSON array format:
<c:if test="${not empty errors}">
<script>displayErrors(errors);</script>
</c:if>
Or let JSP assign it as a JS variable and let JS handle it further. Something like:
<script>
var errors = ${errors};
if (errors.length) {
displayErrors(errors);
}
</script>
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.
You can achieve similar kind of behavior by using following method. While sending response itself you can provide JS events.
PrintWriter out = response.getWriter();
out.println("<tr><td><input type='button' name='Button' value='Search' onclick=\"searchRecord('"+ argument + "');\"></td></tr>");
So when you click on Search button, search record method of JS will be called.