How to integrate Java code with Javascript?

Asked

Viewed 867 times

0

//retorna o usuário logado no sistema
public class ContextObject {

    public static Usuario getUsuario() {
        ContextObject contextObject = ContextFactory.getContextObject();
        return contextObject.usuario;
    }    

}
//mostra em uma função alert() o usuário logado
<script> alert(ContextObject.getUsuario()); </script>

Since these two codes are in different files.

I’m doing this but it’s not right, how should I do it? I need to take the return of java code and show what is coming in the function alert javascript.

  • 1

    If the javascript code is executed on the client side and the java code is on the server side, it seems to me a difficult task to perform. In this case AJAX may be a solution to this problem.

1 answer

1


Initially you should have a method that returns a json with the desired data, can be in the same class.

But it would involve a REST configuration that I won’t quote here, but you can find in this link and here.

The method you write down your method with @GET and @Produces("application/json") and the class with the annotation @Path("/caminho"). You should also note your user class with @XmlRootElement.

In your javascript you can call the method via HTTP GET. Something like that:

$(function () {
    $.getJSON("/caminho", function(data) {
        alert(data.nome);
    });
});
  • date would be the class name?

  • creates the Rest for me? I’ve never done anything like :(

  • No, data is the argument I’m passing to the method. I used data because it means data in Portuguese. It’s kind of a pattern, but it can be the name of the class if you want. About REST I posted two links that teach you to do, just follow the tutorial.

Browser other questions tagged

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