在hibernate中从数据库中检索图像

时间:2017-05-21 11:42:58

标签: hibernate jsp servlets

这是我的名为 showimage.java

的servlet
 protected void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {

        session=sessionFactory.openSession();
        session.beginTransaction();         

        try{            
        Tab person = (Tab) session.get(Tab.class,new Integer(1));     
        byte[] photoBytes = person.getEImage();        
        try (ServletOutputStream sos = res.getOutputStream()) {
             sos.write(photoBytes);
            }
        }
        catch(Exception e){
        e.printStackTrace();        
        session.getTransaction().commit();
        session.close();
        a++;
        }        
}

以下是我的jsp页面名为 showimage.jsp 。我在图像colomn中从数据库获取相同的图像,因为此 Tab person =(Tab)session.get( Tab.class,new Integer(1)); 。有人建议替换 new Integer(1),这样每次调用servlet时,我都能获得新的Id  从数据库动态。

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP List Users Records</title>
</head>
<body>
    <sql:setDataSource
        var="myDS"
        driver="com.mysql.jdbc.Driver"
        url="jdbc:mysql://localhost:3306/project"
        user="root" password="lovemapa!23"
    />

    <sql:query var="listUsers"   dataSource="${myDS}">
        SELECT * FROM tab;
    </sql:query>

    <div align="left">
        <table border="1" cellpadding="5">
            <caption><h2>List of users</h2></caption>
            <tr>
                <th>ID</th>
                 <th>Image</th>
            </tr>
            <c:forEach var="user" items="${listUsers.rows}">
                <tr>
                    <td><c:out value="${user.E_id}" /></td>
                   <td><img src="showimage?id=${user.E_id}"></td>
                </tr>
            </c:forEach>
        </table>
    </div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

您将ID作为网址参数传递:showimage?id=${user.E_id}。 在您的servlet中,您可以将此值检索为

Integer id = new Integer(req.getParameter("id"));
Tab person = (Tab) session.get(Tab.class, id);