0

コメントは 1 つしか取得できず、新しいコメントが投稿されると更新されますが、投稿されたすべてのコメントを表示したいのですが、どこが間違っていますか?

コメントサーブレット

  String comment=request.getParameter("myTextarea");  //i stored myTextarea in string  comment            
   ArrayList<String> al1 = new ArrayList<String>();
    ArrayList emp_list =new ArrayList();                                     
     al1.add(comment);                     
      emp_list.add(al1);                                         
      request.setAttribute("empList",emp_list);        
      String nextJSP = "/result.jsp";//goes to result.jsp
     RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
    dispatcher.forward(request,response);

結果.jsp

    <%
     try{
      int i=0;
      if(request.getAttribute("empList")!=null)
       {
       ArrayList al3 = (ArrayList)request.getAttribute("empList");
        Iterator itr = al3.iterator();
        while(itr.hasNext()){
        ArrayList empList = (ArrayList)itr.next();
         String newcomment="";
          try{
          newcomment=(String)empList.get(i++);
          }
         catch(Exception e){
          }   
        try{
      out.println(newcomment);// i am getting only one comment here
         }
     catch(Exception e){
     }   
     }
    }
  }//end of try block
    catch(Exception e){
   out.println(e); 
   }
   %>
4

2 に答える 2

2

まず第一に、あなたの Java では、 にコメントを 1 つだけ入れているように見えます。そのため、コメントがempList1 つしか表示されません。

URLが次のように見えると仮定してwww.some.url/resource?myTextarea=somestring...

String comment=request.getParameter("myTextarea"); 
//so now comment equals to "somestring"

ArrayList<String> al1 = new ArrayList<String>();
ArrayList emp_list =new ArrayList();                                     
al1.add(comment);
//now al1 equals ["somestring"]                     

emp_list.add(al1);
//now emp_list equals [["somestring"]]

emp_list には 1 つのコメントしかないので、jsp には 1 つのコメントが含まれます。

さらに、あなたがjspで書いたコードは奇妙です.なぜあなたは持っているの newcomment=(String)empList.get(i++);ですか? コメントを格納する特別なデータ構造がない限り、このコードですぐに OutOfIndexException が発生すると確信しています。現在、データ構造にはリストのリストがあり、リスト内の各リストには次のようなコメントが 1 つ含まれているように見えますか? [["comment1"], ["comment2"], ["comment3"], ...]

于 2012-04-19T08:41:21.737 に答える
0

jstlを使用しないのは間違っています:)

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<c:forEach items = "${empList}" var = "comment">
  <c:out value = "${comment}"/>
</c:forEach>

私のコードがあなたの例では機能しないことはわかりますが、私の質問は、コメントをリストするためだけにリストにリストがあるのはなぜですか?

于 2012-04-19T08:19:41.833 に答える