I have no idea how to do this and found some examples of how to call it however creating the script in java code (what I don't want), in ASP.NET I would use this code ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "info only", "alert('" + message + "');", true); to call my script + pass parameters and would work fine as I wished. However I have no idea of how to do this in java. Thank you
-
2Can you please elaborate do you want to call JavaScript code from JSP or from Servlet or from a simple class? What exactly are you trying to do?gprathour– gprathour2014-06-18 10:31:44 +00:00Commented Jun 18, 2014 at 10:31
-
From my Servlet, I'm sorry if i wasnt clearuser3362533– user33625332014-06-18 10:50:58 +00:00Commented Jun 18, 2014 at 10:50
-
@user3362533 still not clear enough. A servlet runs on the server (1) and produces in most cases some html-code wich may or may not include js-code that is sent to the client an is rendered/evaluated on the client side (2). So where should the js be executed, (1) or (2) ?A4L– A4L2014-06-18 10:53:37 +00:00Commented Jun 18, 2014 at 10:53
-
I was thinking on just call my function from Servlet passing some parameters, no creating one in my server side... My function is in my JSP, I'm trying to avoid create my javascript code in my server side. so (1) –user3362533– user33625332014-06-18 10:55:59 +00:00Commented Jun 18, 2014 at 10:55
2 Answers
Simply by googling I found this link which provides good examples on how to invoke a javascript file.
Here is a simple example to get you going:
import java.io.*;
import javax.script.*;
public class App
{
public static void main(String[] args)
{
String file = "javascript.js";
try
{
ScriptEngine engine =
new ScriptEngineManager().getEngineByName("javascript");
FileReader fr = new FileReader(file);
engine.eval(fr);
}
catch(IOException ioEx)
{
ioEx.printStackTrace();
}
catch(ScriptException scrEx)
{
scrEx.printStackTrace();
}
}
}
3 Comments
onload event.I saw that it wasn't possible to call my javascript via Servlet, however if I just pass my parameters using my resp/req objects and retrieve them in my JSP page and my JSP page call myt javascript method would work. Anyway here is the code I used:
Check if my params arent empty and call my script
<c:if test="${not empty errors}">
<script>displayErrors(errors);</script>
</c:if>
The script I would like to call (sample):
<script>
var errors = ${errors};
if (errors.length) {
displayErrors(errors);
}
</script>
And I found this answer here (How to call function of JavaScript from servlet)
Big thanks for everybody