Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call function of JavaScript from servlet

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 have written contoller in servlet.

How to call the function of that JavaScript file from my servlet.

like image 430
Sunil Kumar Sahoo Avatar asked Apr 21 '12 11:04

Sunil Kumar Sahoo


3 Answers

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.

like image 158
Ravindra Gullapalli Avatar answered Oct 09 '22 10:10

Ravindra Gullapalli


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.

like image 38
Ved Avatar answered Oct 09 '22 10:10

Ved


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.

like image 29
BalusC Avatar answered Oct 09 '22 11:10

BalusC