How to display image in jsp saved in db using spring and hibernate


How to display image in jsp saved in db using spring and hibernate:

I assume you know how to integrate spring with hibernate and how to write simple CRUD operation code using it
please Click here for spring-hibernate integration example.

In Jsp/html page

-------------------------------------------------------------------------------------------------------------------------

 <!DOCTYPE>
 <html>
 <head>
 </head>
 <body>

 <img src="getImagefromDB?personid=20" width="400" height="400" alt="image">

 </body>
 </html>

  • This getImagefromDB url must match in controller
  • For example purpose I have taken persoonid as "20".
  • In real-time project you must send this id dynamically as:

<img src="getImagefromDB?personid=${pid}" width="400" height="400" alt="image">



In controller write the method to get that image from DB and display in jsp.

In Controller
-------------------------------------------------------------------------------------------------------------------------

 @Controller
 public class ShowImageController {


 @Autowired
 GetImageService getImageService;


 //getImagefromDB url will map the img src url from jsp where we want to display the image

 @RequestMapping("getImagefromDB")
 public void getBlobImagefromDB(HttpServletResponse response,
           @RequestParam("personid") int personid) throws IOException
 {
       
 // below getImageService.getImageFromDB method will call DAO method and will return  blob image from db as byte[].

   byte[] photo = getImageService.getImageFromDB(personid);

OutputStream outputStream=response.getOutputStream();
outputStream.write(photo);
outputStream.flush();
outputStream.close();
}

   }




In DAO
-------------------------------------------------------------------------------------------------------------------------

  @Repository
  public class ImageDAOImpl implements ImageDAO{

   @Autowired
   SessionFactory sessionFactory;

   @Override
   public byte[] getIamgeFromDB(int personid){
   Session session=sessionFactory.openSession();
   Query query=session.createQuery("select photo from Person where personid=?");
   query.setParameter(0,personid);
   byte[] photo=(byte[])query.uniqueResult();
   session.close();
   return photo;
  }
 }






Comments