数据库表中Image图像的页面显示

2303阅读 0评论2008-11-14 xinyu391
分类:Java

数据库表中Image图像的页面显示

在主jsp或servelt或bean中:从数据库中查询Image字段,以byte数组形式读取
byte[] bytes = results.getBytes(index);
session.setAttribute("imgBlob", bytes);

显示图像的servlet代码

public class ShowImage extends HttpServlet {
    private static final String CONTENT_TYPE = "image/gif";

    private transient final Log log = LogFactory.getLog(getClass());

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        if (log.isDebugEnabled()) {
            log.debug("Entering 'showIcon' method");
        }
        try {
            response.setContentType(CONTENT_TYPE);
            byte[] bytes = (byte[]) request.getSession().getAttribute("imgBlob");
            response.setContentLength(bytes.length);
            ServletOutputStream op = response.getOutputStream();
            op.write(bytes);
            op.flush();
            op.close();
        } catch (Throwable e) {
            log.error(e);
        }

    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}


web.xml中servelt映射:


<servlet>
        <servlet-name>showImage</servlet-name>
        <servlet-class>com.tjad.servlet.ShowImage</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>showImage</servlet-name>
        <url-pattern>/showImage</url-pattern>
    </servlet-mapping>


在jsp页面中显示图像使用:

<img src="showImage" width="100" height="150"/>


上一篇:系统安全之UNIX下入侵检测方法
下一篇:ClipboardManager