【问题标题】:I want to retrieve image from database and display it in JSP using <img> tag. I am using my sql我想从数据库中检索图像并使用 <img> 标记将其显示在 JSP 中。我正在使用我的 sql
【发布时间】:2015-09-22 21:50:39
【问题描述】:

我想从数据库中检索图像并使用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();
        }
    }
}    

此代码直接显示图像。但我想要这条路。所以我可以在任何我想要的地方显示它。还有其他方法可以在动态网页中显示此图像吗?

【问题讨论】:

    标签: java html mysql jsp servlets


    【解决方案1】:

    路径取决于您的 servlet 在 web.xml 中的映射方式(因为我在您的代码中没有看到任何注释)。另一种 - 但相当不鼓励 - 的方式是使用数据 URI。见I want to retrieve image from mysql database using servlet and show that image along with that user details in table

    【讨论】:

    • 如何找到图片的数据URI
    • 阅读链接问题中的答案和链接。学习。做好功课。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    • 2015-11-23
    • 2016-02-07
    • 2013-01-13
    • 2014-09-22
    • 2017-04-28
    • 2015-11-22
    相关资源
    最近更新 更多