Call Java method in Javascript

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
}

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

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

    
asked by anonymous 25.06.2014 / 16:50

2 answers

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 , which does not explicitly work with 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 an earlier comment: send data via an HTTP request in JSON format.

Conceptually, what you need to do is pretty simple: serialize the content you want to send to JavaScript through a < a href="http://www.json.org/java/"> Java method and then, there on the front end, in JavaScript code, you can do something like this using jQuery library :

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

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

The response parameter of the success method is the data sent by your Java application. From there, you can work as you see fit.

In this link I take a pretty similar approach that can be useful.

    
25.06.2014 / 18:24
3

Expensive, your mission in the way you expect is impossible. But you can do this by using asynchronous requests quite simply, see some examples

    
25.06.2014 / 17:05