简体   繁体   中英

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

I want to retrieve image from database and display it in JSP using img tag. I am using 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();
        }
    }
}    

This Code display image directly. But I want the path. So I can display it wherever I want. Are there any other ways to display this image in a dynamic web page?

The path depends on how your servlet is mapped in web.xml (as I don't see any annotations in your code). The other - but rather discouraged - way is to use data URI. See I want to retrieve image from mysql database using servlet and show that image along with that user details in table

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM