使用servlet从mysql中检索图像(blob)并在jsp中显示它

时间:2016-07-13 13:54:07

标签: java mysql jsp

如何从数据库中检索图像(带有blob数据的mysql)并在servlet中以表格形式<h2>Just some shapes : </h2> <div class="square"></div> <div class="triangle"></div>设置它并在JSP页面上显示它,动态创建表格(基于我的数据库数据)(虽然我不确定它是否可以实现)但如果它是可以实现的,我该怎么做呢?如果无法实现。建议的答案是什么?非常感谢您的帮助。 这是我的代码:

(PrintWriter pw = response.getWriter(); pw.write("<img src=""/>"); )

这是我的豆子

     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
             byte[] binaryStream;
        ArrayList<RetrievingPost> combine=new ArrayList<RetrievingPost>();

           try{
                             // Register JDBC driver
                             Class.forName("com.mysql.jdbc.Driver");

                             // Open a connection
                             Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/asq?characterEncoding=UTF-8&useSSL=false", "root", "root");

                             // Execute SQL query
                             Statement pst = connection.createStatement();
                             String sql;
                             sql = "select profilepic, displayname, r.userId, friendId from registration r inner join friendlist fl on r.userId=fl.userId where r.emailAddress='" + emailAddress + "'";
                             ResultSet rs = pst.executeQuery(sql);

                             // Extract data from result set
                             while(rs.next()){
                                //Retrieve by column name
                         Retrieving retrieve=new Retrieve();
                                userId  = rs.getInt("userId");
                                 System.out.println(userId+"---------userId-------");
                                friendId =rs.getInt("friendId");
                                displayname=rs.getString("displayname");

                              binaryStream = rs.getBytes("profilepic");
    retrieve.setFriendId(friendId);
    retrieve.setDisplayName(displayname);
     retrieve.setBinaryStream(binaryStream);
     Combine.add(retrieve);
                        }


                             // Clean-up environment
                             rs.close();
                             pst.close();
                             connection.close();
                          }catch(SQLException se){
                             //Handle errors for JDBC
                             se.printStackTrace();
                          }catch(Exception e){
                             //Handle errors for Class.forName
                             e.printStackTrace();
                          }finally{
                             //finally block used to close resources
                             try{
                                if(stmt!=null)
                                   stmt.close();
                             }catch(SQLException se2){
                             }// nothing we can do
                             try{
                                if(conn!=null)
                                conn.close();
                             }catch(SQLException se){
                                se.printStackTrace();
                             }//end finally try
                          } //end try

        for(int j=0;j<combine.size();j++){
          PrintWriter pw = response.getWriter();
                                       pw.write("<HTML><BODY>");
                                       pw.write("<TABLE border='1'>");
                                       pw.write("<TR>");
                                       pw.write("<TD>");



                                       pw.write(combine.get(i).getDisplayname());
                                       pw.write("</TD>");
                                    //if possible, i would like to display my image into the table
                                       pw.write("<TD>");
                                       String tPosted=combine.get(i).getTimePosted().toString();
                                       pw.write(tPosted);
                                       pw.write("</TD>");
                                       pw.write("</TR>");
                                     }}
getServletContext().getRequestDispatcher("/DisplayingImage.jsp").include(request, response);}

1 个答案:

答案 0 :(得分:0)

查看此question的答案。专注于servlet说明,因为您将它用于您的页面。

基本上,要遵循的流程是:

  1. 创建一个servlet,其唯一目的只是调度图像,并确保通过GET参数接收用户的id(例如,创建一个名为 ImageServlet 的servlet,参数 userId

    @WebServlet("/ImageServlet")
    public class ImageServlet extends HttpServlet {
    //...
       public void doGet( HttpServletRequest request, HttpServletResponse response){
          Integer userId = Integer.parseInt( request.getParameter( "userId" ) );
    
  2. 在该servlet中,连接到您的数据库。

    public void doGet( /*...*/ ){
       Integer userId = //...
       //super method to extract the data from your DB
       RetrievingPost userInfo = new UserDAO( ).fetchById( userId );
    
  3. 超级重要将回复的mime类型标记为“image / jpg”(或png,jpeg等)。

    response.setContentType( "image/jpg" );
    
  4. 提取图像并将其写入outputStream对象。使用一些I / O缓冲区来帮助您

    BufferedOutputStream bos = new BufferedOutputStream( response.getOutputStream( ) );
    bos.write( userInfo.getBinaryStream( ) );
    bos.flush( );
    bos.close( );
    

    修改

  5. 在JSP页面(或HTML)中放置一个引用servlet的图像标记。

    <!--Set the param "userId" to a custom one with JS or JSP-->
    <img src="/my_project/ImageServlet?userId=50"/>