在jsp上通过servlet显示数据库中的图像

时间:2013-09-07 08:03:48

标签: java image servlets

我无法将我的图像从数据库显示到我的jsp页面上,我仍然无法解决问题所在,请帮忙。

我的servlet:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        DBConnection db = new DBConnection();
        Connection conn;
         try {
             conn =  db.getDbConnection();
            PreparedStatement ps = conn.prepareStatement("select stu_image from student_images_table where STU_REG_NO = ?");
            String id = request.getParameter("studentregno");
            ps.setString(1,id);
            ResultSet rs = ps.executeQuery();
            rs.next();
            Blob  b = rs.getBlob("stu_image");            
            response.setContentType("image/jpeg");
            response.setContentLength( (int) b.length());
           // response.setContentLength(10);
            InputStream is = b.getBinaryStream();
            OutputStream os = response.getOutputStream();
            byte buf[] = new byte[(int) b.length()];
            is.read(buf);
            os.write(buf);
            os.close();
        }
        catch(Exception ex) {
             System.out.println(ex.getMessage());
        }
    }

我的JSP:

<div id="bv_Image1" style="margin:0;padding:0;position:absolute;left:572px;top:31px;width:194px;height:162px;text-align:left;z-index:1;">
                        <img src="ProfileInquiryServlet" id="Image1" alt="" align="top" border="0" style="width:194px;height:162px;"></div>

我的展示:

My Display has no Image

我可以做错什么?

修改 我的Web.xml很大,但也许这可能是相关的;

<servlet>
        <servlet-name>ProfileInquiryServlet</servlet-name>
        <servlet-class>com.kollega.controller.ProfileInquiryServlet</servlet-class>
    </servlet>
     <servlet-mapping>
        <servlet-name>ProfileInquiryServlet</servlet-name>
        <url-pattern>/ProfileInquiryServlet</url-pattern>
    </servlet-mapping>

1 个答案:

答案 0 :(得分:0)

为图像使用一个servlet,并将其传递给studentregno

<img src="ProfileInquiryServlet?studentregno=${param.studentregno}" ...

这是一个单独的请求,因此需要具有该参数。


第一个servlet可以request.setAttribute("regno", "...");,然后在JSP中可以使用${regno}request.getParameter("studentregno")可用${param.studentregno}