How to fetch image from database using Spring MVC

In this article, we will learn how to fetch image from database using Spring MVC. To fetch images from database and display it on the JSP, we need to convert Blob type data into the byte[] array and response as OutputStream. My previous tutorial shows you How to insert image in database using Spring MVC .

In this example, we will create two methods that handle the HTTP request:

  1. listStudent() method will fetch all the students records.
  2. getStudentPhoto() method will fetch each student photo based on their ID.

Similar Post: Spring Boot- Display image from database and classpath

Technologies Used

Find the list of technologies, used in this application

  1. Eclipse Oxygen
  2. Tomcat 9
  3. JDK 8
  4. Maven 3
  5. Spring5.0.2.RELEASE
  6. MySQL Database
  7. JSTL 1.2

Dependencies Required

These are the required dependencies that must be your build path. To get all these dependencies all the following code in your pom.xml.

<project xmlns="" xmlns:xsi=""
	<name>spring-mvc-fetch-image-db Maven Webapp</name>
		<!-- spring mvc dependency -->
		<!-- spring jdbc dependency -->
		<!-- mysql databse connector -->


Project Structure

Final project structure of our application in Eclipse IDE will look like as follows.

How to fetch image from database using Spring MVC

Model Class

Create Student model class and mention its attribute like id, name, age, etc.
package org.websparrow.model;

public class Student {

	// Getters and Setters...
	private int id;
	private String name;
	private int age;

DAO Classes

Create StudentDao interface and define the stuList() method of List<Student> type and getPhotoById(int id) of Blob type.
package org.websparrow.dao;

import java.sql.Blob;
import java.util.List;

import org.websparrow.model.Student;

public interface StudentDao {

	public List<Student> stuList();
	public Blob getPhotoById(int id);


Create an implementation class StudentDaoImpl that implements StudentDao.
package org.websparrow.dao;

import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.websparrow.model.Student;

public class StudentDaoImpl implements StudentDao {

	private JdbcTemplate jdbcTemp;

	public StudentDaoImpl(DataSource dataSource) {
		jdbcTemp = new JdbcTemplate(dataSource);

	public List<Student> stuList() {

		List<Student> list = jdbcTemp.query("SELECT * FROM student", new RowMapper<Student>() {

			public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
				Student stu = new Student();


				return stu;

		return list;

	public Blob getPhotoById(int id) {

		String query = "select photo from student where id=?";

		Blob photo = jdbcTemp.queryForObject(query, new Object[] { id }, Blob.class);

		return photo;


Front Controller & MVC Configuration

I have used annotation based configuration, so the front controller class will be:
package org.websparrow.config;


public class FontControllerConfig extends AbstractAnnotationConfigDispatcherServletInitializer {

	protected Class<?>[] getRootConfigClasses() {

		return new Class[] { WebMvcConfig.class };

	protected Class<?>[] getServletConfigClasses() {

		return null;

	protected String[] getServletMappings() {
		return new String[] { "/" };

And the Spring MVC configuration class will be given below. In this class, we will create a database connection, register the StudentDao and InternalResourceViewResolver.
package org.websparrow.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.websparrow.dao.StudentDao;
import org.websparrow.dao.StudentDaoImpl;

@ComponentScan(basePackages = { "org.websparrow.controller", "org.websparrow.dao" })
public class WebMvcConfig {

	public InternalResourceViewResolver viewResolver() {

		InternalResourceViewResolver vr = new InternalResourceViewResolver();

		return vr;

	public DriverManagerDataSource getDataSource() {

		DriverManagerDataSource ds = new DriverManagerDataSource();

		return ds;

	public StudentDao getStudentDao() {
		return new StudentDaoImpl(getDataSource());


Controller Class

Create a controller class that handles the user request and @Autowired annotation inject an instance of the StudentDao implementation into this controller automatically.
package org.websparrow.controller;

import java.sql.Blob;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.websparrow.dao.StudentDao;
import org.websparrow.model.Student;

public class StudentController {

	private StudentDao stuDao;

	@RequestMapping(value = "/fetch")
	public ModelAndView listStudent(ModelAndView model) throws IOException {

		List<Student> listStu = stuDao.stuList();

		model.addObject("listStu", listStu);

		return model;

	@RequestMapping(value = "/getStudentPhoto/{id}")
	public void getStudentPhoto(HttpServletResponse response, @PathVariable("id") int id) throws Exception {

		Blob ph = stuDao.getPhotoById(id);

		byte[] bytes = ph.getBytes(1, (int) ph.length());
		InputStream inputStream = new ByteArrayInputStream(bytes);
		IOUtils.copy(inputStream, response.getOutputStream());

JSP Page

On the JSP, iterate the list returned by controller class using JSTL.

<%@ taglib uri="" prefix="c"%>
<%@page isELIgnored="false"%>
	<h2>How to fetch image from database using Spring MVC</h2>

	<table border="1">
		<c:forEach var="student" items="${listStu}">
				<td><img width="100" height="100" src="getStudentPhoto/<c:out value='${}'/>"></td>



Run your application and hit the below URL in your browser address bar.

URL: http://localhost:8090/spring-mvc-fetch-image-db/fetch

You will get the following result.

How to fetch image from database using Spring MVC


  1. Spring @Autowired annotation example
  2. Data access with JDBC
  3. Class JdbcTemplate
  4. How to display Image in JSP from database using Struts 2

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.