Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我想从数据库中检索图像,并使用标记在JSP中显示它。我正在使用我的sql_Java_Html_Mysql_Jsp_Servlets - Fatal编程技术网

Java 我想从数据库中检索图像,并使用标记在JSP中显示它。我正在使用我的sql

Java 我想从数据库中检索图像,并使用标记在JSP中显示它。我正在使用我的sql,java,html,mysql,jsp,servlets,Java,Html,Mysql,Jsp,Servlets,我想从数据库中检索图像,并使用img标记在JSP中显示它。我正在使用mySql public class DisplayImage extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //PrintWriter pw = response.getWri

我想从数据库中检索图像,并使用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,但并不鼓励。请参见

如何查找图像的数据URI?请阅读链接问题中的答案和链接。学习做你的家庭作业。