簡體   English   中英

我想從數據庫中檢索圖像並在JSP中使用顯示它 <img> 標簽。 我正在使用我的SQL

[英]I want to retrieve image from database and display it in JSP using <img> tag. I am using my sql

我想從數據庫中檢索圖像,並使用img標簽在JSP中顯示它。 我正在使用mySql。

public class DisplayImage extends  HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //PrintWriter pw = response.getWriter();
        String connectionURL = "jdbc:mysql://localhost:3306/demodb";;
        java.sql.Connection con=null;
        try{  
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con=DriverManager.getConnection(connectionURL,"root","0321");  
            Statement st1=con.createStatement();
            ResultSet rs1 = st1.executeQuery("select photo from contacts where  contact_id='2'");
            String imgLen="";
            if(rs1.next()){
                imgLen = rs1.getString(1);
                System.out.println(imgLen.length());
            }  
            rs1 = st1.executeQuery("select photo from contacts where contact_id='2'");
            if(rs1.next()){
                int len = imgLen.length();
                byte [] rb = new byte[len];
                InputStream readImg = rs1.getBinaryStream(1);
                int index=readImg.read(rb, 0, len);  
                System.out.println("index"+index);
                st1.close();
                response.reset();
                response.setContentType("image/jpg");
                response.getOutputStream().write(rb,0,len);
                response.getOutputStream().flush();  
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
}    

此代碼直接顯示圖像。 但是我要走這條路。 所以我可以在任何地方顯示它。 還有其他方法可以在動態網頁中顯示此圖像嗎?

路徑取決於您的servlet在web.xml中的映射方式(因為我在代碼中看不到任何注釋)。 另一種方法(但不建議使用)是使用數據URI。 請參閱我要使用servlet從mysql數據庫中檢索圖像,並在表中顯示該圖像以及該用戶的詳細信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM