Calling Java method in Javascript

Asked

Viewed 4,019 times

3

I have a problem, and I needed to call a Java method inside a Javascript file.

Java example:

public void Inserir(User user)
{
    //insere usuario
}

Need, via a file . js, send the object to the Java class responsible for the Insert method, and perform user insertion.

PS: Unfortunately I cannot perform via HTML, JSF, or JSP.

2 answers

3

Dear, your mission the way you expect it is impossible. But you can do it using asynchronous requests very simply, see some examples

  • Thanks... it’s really seeing here that it’s impossible even. I’ll see these examples you sent me, thank you.

  • It is possible to communicate javascript with java via json?

  • @Ericosouza Bingo! I explained it better in my reply.

2


Executing some Javascript feature explicitly in a Java application is impossible. In fact, this is not restricted only to Java, but to any Server-Side language with the exception of Node.JS, that does not expressly work with the front-end.

To solve your problem, you can use AJAX. A very simple way to solve this is with a solution that you yourself proposed in a comment from before: send data via an HTTP request in JSON format.

Conceptually, what you need to do is very simple: serialize the content you want to send to Javascript through a java method and then, there on the front end, in Javascript code, you can do something like this using the jQuery library:

$.ajax({
   url: 'localhost/user',
   success: function (response) {
       console.log(response);
   }
});

Being url the address you provide your JSON data to - through your Java application - and the method success to work with the return if the request is made, suggestively, successfully.

The parameter response of the method success are the data sent by your Java application. From there, you can work as well as understand.

At this link I take a very similar approach that might be useful.

  • Thanks @Guilherme this helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.