Returning a JSON from a Servlet



如何从 Servlet 返回 JSON?这是我的代码,但有些东西不起作用,我想我在 JS 代码中犯了错误,但我不知道如何纠正它。

这是奴役

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;        
});

这是Utente对象

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;
}
$.get("UserServlet", function (response) {                                                                                      
  document.getElementById("endusername").innerHTML = utente.nome;        
});

我相信您只想使用 utente.nome 设置字段"最终用户名"。所以,你在这里不需要innerHTML。

document.getElementById("endusername").innerHTML

应该是

document.getElementById("endusername").value

PS不擅长语法。

最新更新