2012-10-05 38 views
0

我有一個java servlet將數組傳遞給一個jsp頁面,在該jsp頁面上它顯示了一堆結果。我試圖做的是當它打印出來打印一個鏈接,所以我可以用它作爲參數。在我的情況下,它打印出一大堆實驗室類,我想要發生的是他們點擊與該實驗室相關的鏈接,然後我單擊鏈接並可以在sql語句中使用該lab.id。Servlet Jsp數組打印鏈接

這裏是正在打印的數組的代碼進行

這裏是servlet

private void sendBack(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    HttpSession session = request.getSession(true); 

     //Set data you want to send back to the request (will be forwarded to the page) 
    //Can set string, int, list, array etc. 
    //Set data you want to send back to the request (will be forwarded to the page) 
    //Can set string, int, list, array etc. 
    String sql = "SELECT s.name, l.time, l.day, l.room" + 
       " FROM lab l, subject s, user_lab ul" + 
      " WHERE ul.user_id=" + (Integer)session.getAttribute("id") +" AND ul.lab_id ="+ "l.id"+" AND l.subject_id ="+"s.id"; 

    try{ 
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root",""); 
    System.out.println("got boobs"); 
    System.out.println(session.getAttribute("id")); 

     Statement stmt = con.createStatement(); 
     ResultSet res = stmt.executeQuery(sql); 
     System.out.println(res); 
     ArrayList<String> list1 = new ArrayList<String>(); 
     if (res.next()){ 
      do{ 
       list1.add(res.getString(1) + " " + res.getString(2) +" "+ res.getString(3) + " " + res.getString(4)); 
       System.out.print(res.getString(1) + res.getString(2)); 
      }while(res.next()); 
     System.out.println("Outside"); 
     String[] arr = list1.toArray(new String[list1.size()]); 
     request.setAttribute("res", arr); 
     } 




    }catch (SQLException e) { 
    } 
    catch (Exception e) { 
    } 


    //Decides what page to send the request data to 
    RequestDispatcher view = request.getRequestDispatcher("Lecturer_labs.jsp"); 
    //Forward to the page and pass the request and response information 
    view.forward(request, response); 

,這裏是JSP頁面

<h3>Manage Labs</h3> 
<table> 
<% String[] list1 = (String[])request.getAttribute("res"); 
     if(null == list1){%> 

<% 
     }else{ 
     for(int i=0; i<list1.length; i++) 
     { %> 
     <tr><%out.println(list1[i] + "<br/>");%></tr>   
    <% } 
     } 
     %> 
     </table> 

所以我怎樣才能得到它的打印作爲通過參數的鏈接的結果

回答

2

要將結果顯示爲鏈接傳遞參數id,每一個環節可能是這樣的:

<a href="/myapp/mypage.jsp?id="<%out.println(list1[i]);%>">Link <%out.println(list1[i]);%></a> 

但怎麼看這個笨重的外觀。

JSTL tags可以消除所有這些scriptlet代碼:

<c:forEach items="${res}" var="id"> 
    <tr><td><a href="/myapp/mypage.jsp?id=${id}">Link ${id}</a></td></tr> 
</c:forEach> 
+0

不幸的是,我們是不允許使用JSTL :( – user1393064

+0

然後使用 - > 的(一個String:鏈接){ 的System.out。的println( 「​​」); 的System.out.println(一個或多個); 的System.out.println(「」);} 原始 JSP是痛苦 –

+0

上。 é問題,它沒有傳遞到URL的身份證,我知道在PHP它確實要傳遞變量是Java一樣嗎? – user1393064