Answer the question
In order to leave comments, you need to log in
Calling a java class function from javascript code?
Hello everyone,
I'm struggling with a problem, please help me solve it.
Problem essence:
There is a servlet. On the client page, some content needs to be updated every n seconds. The updated information is taken from the execution of the function described in the java class on the server.
how to call java class function in javascript code written in jsp file?
ps If something is not clear written - I'm sorry, I can add.
Thanks in advance!
Answer the question
In order to leave comments, you need to log in
Java class exists on the server side, javascript code - on the client side => the only way to make a method call is by request. For example, you can write a helper servlet that will process ajax requests and call the required java class method.
You cannot directly call java code from client-side javascript. You can send an http request from the browser to the server, where the servlet will process it and return the result in some browser-friendly format like xml or json. In the same jquery, this is not difficult to do:
$.get("/getTimeLordNameByIndex", { index: 1 })
.done(function( data ) {
alert( "First timelord is " + data ); // Doctor?
});
@WebServlet("/getTimeLordNameByIndex")
class GetTimeLordNameByIndex extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String index = req.getParameter("index");
if (index.equals("1")) {
resp.getWriter().write("Doctor");
} else {
throw new ServletException("Can be only one!");
}
}
}
should be updated?
setTimeout(location.reload.bind(location), 1000)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question