gpt4 book ai didi

java - 如何在servlet中使用json对象返回项目数组以及如何使用jquery显示

转载 作者:行者123 更新时间:2023-12-01 04:51:48 24 4
gpt4 key购买 nike

我需要将一些项目从我的数据库传递到网页。为此,我使用 json 对象将项目从 servlet 传递到 jquery。但我遇到的问题是,

  • 如果数据库包含更多元素
  • 那么我显然需要使用ArrayList
  • 当我使用 ArrayList 时,我不知道如何通过 JSON 传递元素。

我的代码是:

    PrintWriter out = response.getWriter();
response.setContentType("text/html");
response.setHeader("Cache-control", "no-cache, no-store");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "-1");

response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET");
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
response.setHeader("Access-Control-Max-Age", "86400");

Gson gson = new Gson();
JsonObject myObj = new JsonObject();

ArrayList<Commenter> commentInfo;
try {
commentInfo = commenting(uname,message,itemId,albumId);
JsonElement commentObj = gson.toJsonTree(commentInfo);
boolean nonNullElemExist= true;
for (Commenter s: commentInfo) {
if (s == null) {
nonNullElemExist = false;
break;
}
}
if(nonNullElemExist == false){
myObj.addProperty("success", false);
}
else {
myObj.addProperty("success", true);
}
myObj.add("commentInfo", commentObj);
out.println(myObj.toString()); // I think problem is in this statement

out.close();
} catch (ClassNotFoundException | SQLException e) {
System.out.println( "Error --> " + displayErrorForWeb(e));
}

方法是:

   private ArrayList<Commenter> commenting(String uname,String message,int itemId,int albumId) throws ClassNotFoundException, SQLException {
ArrayList<Commenter> commentList = new ArrayList<Commenter>();
Connection conn = null;
conn=prepareConnection();
PreparedStatement stmt = null;
String sql = null;

try {
StringBuilder sb1=new StringBuilder(1024);
sb1.append("insert into ").append(uname.trim()).append("comments values(?,?,?)");
String sql1=sb1.toString();
PreparedStatement stmt1 = conn.prepareStatement(sql1);
stmt1.setString(1,uname);
stmt1.setString(2,message);
stmt1.setInt(3,itemId);

StringBuilder sb=new StringBuilder(1024);
sb.append("select * from ").append(uname.trim()).append("comments");
sql=sb.toString();
stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();

while(rs.next()){
Commenter comment = new Commenter();
comment.setUname(rs.getString("uname").trim());
comment.setComment(rs.getString("comment").trim());
commentList.add(comment);
}

rs.close();
stmt.close();
stmt = null;


conn.close();
conn = null;

}
catch(Exception e){System.out.println( "Error --> " + displayErrorForWeb(e));}

finally {

if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlex) {
System.out.println( "Error --> " + displayErrorForWeb(sqlex));
}

stmt = null;
}

if (conn != null) {
try {
conn.close();
} catch (SQLException sqlex) {
System.out.println( "Error --> " + displayErrorForWeb(sqlex));
}

conn = null;
}
}

return commentList;

}

jquery 是:

  $.ajax({
type: "GET",
url: "Comments",
data:'comm='+encodeURIComponent(comm)+'&'+'data-id='+encodeURIComponent(dataid)+'&'+'data-alid='+encodeURIComponent(dataalid),
dataType: "json",
success: function( data, textStatus, jqXHR)
{
if(data.success)
{
/* $.each(data, function(i, item)
{*/

var newcommhtml = '<div id="c0'+thecid+'" class="cnew clearfix"> <section class="c-author">';
newcommhtml = newcommhtml + '<h3>Anonymous</h3>';
newcommhtml = newcommhtml + '<span class="pubdate">'+month+' '+day+', '+year+'</span> </section>';
newcommhtml = newcommhtml + '<section class="c-content">';
newcommhtml = newcommhtml + '<img src="images/green-avatar.png" alt="avatar" width="80" height="80" class="ava">';
newcommhtml = newcommhtml + '<p>'+nl2br(data.commentInfo.comment)+' '+nl2br(data.commentInfo.itemId)+'</p> </section></div>';
/*newcommhtml = newcommhtml + '<p>'+nl2br(item.commentInfo.comment)+' '+nl2br(item.commentInfo.itemId)+'</p> </section></div>';
});
*/
var thelm = "#c0"+thecid;
commwrap.append(newcommhtml);
$(thelm).hide().fadeIn('slow');

setTimeout(function() { $(thelm).addClass('green'); }, 800);

$("#comm").val("");
thecid++;

if(errorspan.html() != null) {
errorspan.remove();
}
}

},
error: function(jqXHR, textStatus, errorThrown)
{
alert("error"+errorThrown);
console.log("Something really bad happened " + textStatus);
},
});

如果我使用 $each() success block 根本不起作用。

请任何人告诉我如何为这个案例做这些事情......谢谢......

最佳答案

使用 new Gson().toJson(object) 方法将 ArrayList 转换为 json。现在你将得到一个 jsonobjects 的 jsonarray,然后你可以将它像 json 一样传递到服务器,反之亦然。

数组列表是一个集合,所以遵循这个

Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();
Collection<Integer> ints2 = gson.fromJson(json, collectionType);

gson user guide

要使用 jquery 显示 json,请点击此链接。 Best way to display data via JSON using jQuery

关于java - 如何在servlet中使用json对象返回项目数组以及如何使用jquery显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14831985/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com