现在的位置: 首页 > 综合 > 正文

在jsp中显示数据库Blob字段图片实例

2013年09月04日 ⁄ 综合 ⁄ 共 1729字 ⁄ 字号 评论关闭

第一步:新建一个serverlet,用于获得图片流。代码如下:

public class ImageServlet extends HttpServlet {

    public ImageServlet() {
        super();
    }

    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

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

               doPost(request,response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
    //    PrintWriter out = response.getWriter();
        VideoService service=new VideoService();
        String id=request.getParameter("id");
        byte[] imageData=service.getImageDataById(id);
        if (imageData != null) 
   {  
        response.setContentType("image/png");            
        OutputStream stream = response.getOutputStream();
        stream.write(imageData); 
        stream.flush();
        stream.close();
     } 
   else 
     { 
         response.setContentType("text"); 
        response.getWriter().write("attribute byArr not found"); 
      } 

    }

    public void init() throws ServletException {
        // Put your code here
    }

}


第二步:jsp部分代码如下:

<html>
  <head>
  </head>
 
  <body>
       <%
             VideoService service=new VideoService();
             ArrayList<VideoBean> dataLst=service.getVideListInfoByType("100","1","5");
             if(dataLst==null){
                  System.out.println("dataLst is null...");
             }else{
               for(int i=0;i<dataLst.size();i++){
         %>
         <%=dataLst.get(i).getName()%><br/>
         <img alt="图片" src="imageTest?id=<%=dataLst.get(i).getId()%>"><br/>
         <%
                   System.out.println("name:"+dataLst.get(i).getName());
             }
             }
        %>

  </body>
</html>

抱歉!评论已关闭.