How to integrate a Java code with one in JavaScript?

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>

Given that these two codes are in different files.

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

    
asked by anonymous 05.11.2015 / 12:43

1 answer

1

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

But it would involve a REST configuration that I will not quote here, but you can find this link and here .

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

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

$(function () {
    $.getJSON("/caminho", function(data) {
        alert(data.nome);
    });
});
    
05.11.2015 / 13:16