如何在jsp中显示图像

时间:2017-02-10 05:34:55

标签: mysql jsp servlets

我正在通过以下Servlet方法从mysql数据库中检索图像字节:

然后在jsp页面中显示图像字节。

  

请告诉我如何在jsp页面中使用img标签。

    public byte[] getProfilePicture( int id ) {

    byte[] bytes = null;

    try {

        connection = dataSource.getConnection();
        pst = connection.prepareStatement("SELECT profile_picture FROM users WHERE id = '"+id+"' ");
        resultSet = pst.executeQuery();

        while( resultSet.next() ) {

            bytes = resultSet.getBytes("profile_picture");

        }

    } catch(Exception e) {
        e.printStackTrace();
    }

    return bytes;

}
  

谢谢,我在等待您的回复。

1 个答案:

答案 0 :(得分:0)

只需将其作为Web App中的资源,可以使用JSP / Servlet进行访问。

示例1固定Loaction:

Servlet位置:http://www.cvss.online/captcha

JSP代码:

<div class="six columns">
     <label>Captcha image</label>
     <img src="captcha"> 
</div>

示例2按ID分类的动态位置:

每张图片都有唯一的ID

    ...
    int imgId = Integer.parseInt(request.getParameter("imgId"));
    // Your Logic
    ...

您的示例:

在resultSet.next()块中添加:

byte imageArray[] = rs.getBytes(1);
response.setContentType("image/type"); //type png jif etc
outputStream=response.getOutputStream();
outputStream.write(imageArray);
outputStream.flush();
outputStream.close();

干杯