0

How to return a JSON from a Servlet? This is my code but something is not working, I think I made mistakes in the JS code but I don't know how to correct it.

This is the servlet

protected void doGet(HttpServletRequest request, HttpServletResponse  response)throws ServletException, IOException {

    String enduser = ls.ReturnEndUser();

    Utente user = ls.getUserByUsername(enduser); 
    String json = new Gson().toJson(user);
    System.out.println("il JSON è " + json);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);

}

JS

$.get("UserServlet", function (response) {                                                                                      
document.getElementById("endusername").innerHTML = utente.nome;        
});

And this is the Utente object

public Utente(String username, String nome, String cognome, String email, String password, int gruppo1, int gruppo2, int gruppo3, int gruppo4, int gruppo5,String img_src) {
    this.id_utente = id_utente;
    this.username = username;
    this.nome = nome;
    this.cognome = cognome;
    this.email = email;
    this.password = password;
    this.gruppo1 = gruppo1;
    this.gruppo2 = gruppo2;
    this.gruppo3 = gruppo3;
    this.gruppo4 = gruppo4;
    this.gruppo5 = gruppo5;
    this.img_src= img_src;
}
Dani
  • 57
  • 10

1 Answers1

-2
$.get("UserServlet", function (response) {                                                                                      
  document.getElementById("endusername").innerHTML = utente.nome;        
});

I believe you just want to set the field 'endusername' with utente.nome. So, you don't need innerHTML here.

document.getElementById("endusername").innerHTML

should be

document.getElementById("endusername").value

PS not good with syntaxes.

Himanshu Bhardwaj
  • 4,038
  • 3
  • 17
  • 36
  • Well, the console shows:" Uncaught ReferenceError: utente is not defined" – Dani Apr 21 '18 at 17:51
  • Did you debug js and verified what are you getting in response object for js callback. – Himanshu Bhardwaj Apr 21 '18 at 18:03
  • Yes, from the servlet it returns correctly a JSON; I think that the mistake is still in the js but idk what is wrong – Dani Apr 21 '18 at 18:04
  • Solved! the js is $.get("UserServlet", function (responseJSON) { document.getElementById("endusername").innerHTML = responseJSON.nome; }); – Dani Apr 21 '18 at 18:14