D
D
Denis2013-10-12 19:42:46
JavaScript
Denis, 2013-10-12 19:42:46

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

4 answer(s)
S
serso, 2013-10-12
@serso

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.

B
Boris Vanin, 2013-11-20
@fogone

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?
  });

And the servlet:
@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!");
        }
    }
}

S
Sergey, 2013-10-12
Protko @Fesor

should be updated?

setTimeout(location.reload.bind(location), 1000)

S
sigod, 2013-10-13
@sigod

Here is what my googling came up with: stackoverflow.com/questions/4112686/how-to-use-servlets-and-ajax

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question