2012-09-24 82 views
2

我試圖通過從mysql中獲取數據來構建一個數組。該陣列包含文字和圖片。到目前爲止,一切都很順利,但現在我不知道如何從JSP頁面上的memolist中顯示這些圖片。我能看到的只是一堆字節。讓我們來看看:如何從MySQL中檢索一系列圖像並在JSP中顯示它們

我DBQueries看起來是這樣的:

public static ArrayList<Memo> selectAllMemoList() 
{ 
    DBConnectionPool pool = DBConnectionPool.getInstance(); 
    Connection connection = pool.getConnection(); 
    PreparedStatement ps = null; 
    ResultSet rs = null; 

    String query = "SELECT Users.picture, Users.username, Messages.subject, Messages.date, Messages.msg_id " + 
      "FROM Messages, Users " + 
      "WHERE Messages.uid_fk = Users.uid " + 
      "ORDER BY date DESC"; 
    try 
    { 
     ps = connection.prepareStatement(query); 
     rs = ps.executeQuery(); 

     ArrayList<Memo> memolist = new ArrayList<Memo>(); 

     String dbSqlTimestamp = ""; 

     while (rs.next()) { 
     m.setUserpicture(rs.getString("picture")); 
     m.setUsername(rs.getString("username")); 
     m.setSubject(rs.getString("subject")); 
     m.setDate(dbSqlTimestamp = new SimpleDateFormat("dd-MM-yy HH:mm").format(rs.getTimestamp("date"))); 
     m.setMessageid(rs.getInt("msg_id")); 
     memolist.add(m); 
     } 

     return memolist; 
    } 
    catch (SQLException e){ 
     e.printStackTrace(); 
     return null; 
    }   
    finally 
    { 
     DBUtil.closeResultSet(rs); 
     DBUtil.closePreparedStatement(ps); 
     pool.freeConnection(connection); 
    } 
} 

我MemoShowAll看起來是這樣的:

@Override 
protected void doPost(HttpServletRequest request, 
      HttpServletResponse response) 
      throws ServletException, IOException 
{ 

    HttpSession session = request.getSession(); 

    ArrayList<Memo> memolist = DBQueries.selectAllMemoList(); 

    request.setAttribute("listmemo", memolist); 

    String url = "/restricted/MemoList.jsp"; 

    // forward the request and response to the view 
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url); 
    dispatcher.forward(request, response); 

} 

MemoList.jsp

<z:rows> 
    <core:forEach var="each" items="${listmemo}"> 
    <z:row> 
     <img src="${each.userpicture}" border=0 > 
     <z:label value="${each.username}"/> 
     <z:label value="${each.subject}"/> 
     <z:label value="${each.date}"/> 
    </z:row> 
    </core:forEach> 
</z:rows> 

乾杯, BB

+0

存儲在字段userpicture中的內容是什麼?圖像路徑?和圖像的存儲位置? –

回答

1

我繞過這個問題的方式是使用servlet將圖像公開給客戶端。爲此,您應該將從數據庫檢索到的圖像字節存儲到用戶的session對象中。

在HTML我有< img src="/imageRender?id=someimageid"/ >

因此,當瀏覽器將嘗試渲染圖像,它將使調用/imageRender哪裏我的servlet聽。 servlet將讀取輸入參數,然後根據參數從會話對象中呈現圖像。

一些有用的鏈接如下:

1)Display servlet as img src using session attribute

2)Writing image to servlet response with best performance

要特別注意鏈接2 @BalusC答案在那裏說In the ImageDAO#find() you can use ResultSet#getBinaryStream() to get the image as an InputStream from the database.

你的情況的地方您可以創建一個DAO對象列表,它將表示數據庫中的每一行。

相關問題