如何从mysql中检索一系列图像并在JSP中显示它们

时间:2012-09-24 07:50:14

标签: mysql jsp servlets

我正在尝试通过从mysql中获取数据来构建数组。该数组包括文本和图片。到目前为止一切都很顺利,但现在我不知道如何在JSP页面上的memolist中显示这些图片。我只能看到一堆字节。我们来看看:

我的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

1 个答案:

答案 0 :(得分:1)

我绕过这个问题的方法是使用servlet将图像公开给客户端。为此,您应该将从数据库中检索到的图像字节存储到用户的session对象。

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

因此,当浏览器尝试渲染图像时,它将调用我的servlet监听的/imageRender。 servlet将读取输入参数,然后根据参数从会话对象中呈现图像。

一些有用的链接是:

1)Display servlet as img src using session attribute

2)Writing image to servlet response with best performance

要特别注意将@BalusC回答链接到In the ImageDAO#find() you can use ResultSet#getBinaryStream() to get the image as an InputStream from the database.

的地方

在您的情况下,您可以创建一个DAO对象列表,它将代表db的每一行。