Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在servlet中使用json对象返回项数组以及如何使用jquery显示_Java_Jquery_Json_Servlets - Fatal编程技术网

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

Java 如何在servlet中使用json对象返回项数组以及如何使用jquery显示,java,jquery,json,servlets,Java,Jquery,Json,Servlets,我需要将一些项目从数据库传递到网页。为此,我使用json对象将项目从servlet传递到jquery。但问题是 如果数据库包含更多元素 然后我显然需要使用ArrayList 当我使用ArrayList时,我不知道如何通过JSON传递元素 我的代码是: PrintWriter out = response.getWriter(); response.setContentType("text/html"); response.setHeader("Cache-contro

我需要将一些项目从数据库传递到网页。为此,我使用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));
    }
PrintWriter out=response.getWriter();
response.setContentType(“text/html”);
setHeader(“缓存控制”,“无缓存,无存储”);
setHeader(“Pragma”,“无缓存”);
setHeader(“Expires”、“-1”);
response.setHeader(“访问控制允许原点“,“*”);
setHeader(“访问控制允许方法”、“获取”);
setHeader(“访问控制允许头”,“内容类型”);
setHeader(“访问控制最大年龄”,“86400”);
Gson Gson=新的Gson();
JsonObject myObj=新的JsonObject();
ArrayList commentInfo;
试一试{
commentInfo=评论(uname、message、itemId、albumId);
JsonElement commentObj=gson.toJsonTree(commentInfo);
布尔非NullElemexist=true;
对于(评论人s:commentInfo){
如果(s==null){
nonNullElemExist=false;
打破
}
}
if(nonNullElemExist==false){
myObj.addProperty(“成功”,假);
}
否则{
myObj.addProperty(“成功”,真实);
}
添加(“commentInfo”,commentObj);
out.println(myObj.toString());//我认为问题出在这个语句中
out.close();
}catch(ClassNotFoundException | SQLException e){
System.out.println(“错误-->”+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;

} 
private ArrayList注释(字符串uname、字符串message、int itemId、int albumId)抛出ClassNotFoundException、SQLException{
ArrayList commentList=新的ArrayList();
连接conn=null;
conn=prepareConnection();
PreparedStatement stmt=null;
字符串sql=null;
试试{
StringBuilder sb1=新的StringBuilder(1024);
sb1.追加(“插入”).append(uname.trim()).append(“注释值(?,?)”);
字符串sql1=sb1.toString();
PreparedStatement stmt1=conn.prepareStatement(sql1);
stmt1.setString(1,uname);
stmt1.setString(2,消息);
stmt1.setInt(3,itemId);
StringBuilder sb=新的StringBuilder(1024);
附加(uname.trim())。附加(“注释”);
sql=sb.toString();
stmt=conn.prepareStatement(sql);
ResultSet rs=stmt.executeQuery();
while(rs.next()){
Commenter comment=新的Commenter();
comment.setUname(rs.getString(“uname”).trim();
setComment(rs.getString(“comment”).trim();
添加(注释);
}                                                                        
rs.close();
stmt.close();
stmt=null;
康涅狄格州关闭();
conn=null;
}                                                              
catch(异常e){System.out.println(“错误-->”+displayErrorForWeb(e));}
最后{
如果(stmt!=null){
试试{
stmt.close();
}捕获(SQLException sqlex){
System.out.println(“错误-->”+displayErrorForWeb(sqlex));
}                                                            
stmt=null;
}                                                       
如果(conn!=null){
试试{
康涅狄格州关闭();
}捕获(SQLException sqlex){
System.out.println(“错误-->”+displayErrorForWeb(sqlex));
}                                                      
conn=null;
}                                                       
}             
返回评论列表;
} 
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);
      },
});
$.ajax({
键入:“获取”,
网址:“评论”,
数据:'comm='+encodeURIComponent(comm)+'&'+'data-id='+encodeURIComponent(dataid)+'&'+'data-alid='+encodeURIComponent(dataalid),
数据类型:“json”,
成功:函数(数据、文本状态、jqXHR)
{
if(data.success)
{
/*$。每个(数据、功能(i、项)
{*/
var MHTML='';
NewcomHtml=NewcomHtml+“匿名”;
newcommhtml=newcommhtml+“”+月+“”+日+“”,“+年+”;
NewcomHtml=NewcomHtml+“”;
NewcomHtml=NewcomHtml+“”;
newcommhtml=newcommhtml+''+nl2br(data.commentInfo.comment)+''+nl2br(data.commentInfo.itemId)+'

'; /*newcommhtml=newcommhtml+''+nl2br(item.commentInfo.comment)+'+nl2br(item.commentInfo.itemId)+'

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