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.

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>org.websparrow</groupId>
	<artifactId>spring-mvc-fetch-image-db</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring-mvc-fetch-image-db Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<!-- spring mvc dependency -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>5.0.2.RELEASE</version>
		</dependency>
		<!-- spring jdbc dependency -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>5.0.2.RELEASE</version>
		</dependency>
		<!-- mysql databse connector -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>6.0.6</version>
		</dependency>

		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>spring-mvc-fetch-image-db</finalName>
	</build>
</project>

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.

Student.java
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.

StudentDao.java
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.

StudentDaoImpl.java
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);
	}

	@Override
	public List<Student> stuList() {

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

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

				stu.setId(rs.getInt("id"));
				stu.setName(rs.getString("name"));
				stu.setAge(rs.getInt("age"));

				return stu;
			}
		});

		return list;
	}

	@Override
	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:

FontControllerConfig.java
package org.websparrow.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class FontControllerConfig extends AbstractAnnotationConfigDispatcherServletInitializer {

	@Override
	protected Class<?>[] getRootConfigClasses() {

		return new Class[] { WebMvcConfig.class };
	}

	@Override
	protected Class<?>[] getServletConfigClasses() {

		return null;
	}

	@Override
	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.

WebMvcConfig.java
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;

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

	@Bean
	public InternalResourceViewResolver viewResolver() {

		InternalResourceViewResolver vr = new InternalResourceViewResolver();
		vr.setPrefix("/");
		vr.setSuffix(".jsp");

		return vr;
	}

	@Bean
	public DriverManagerDataSource getDataSource() {

		DriverManagerDataSource ds = new DriverManagerDataSource();
		ds.setDriverClassName("com.mysql.jdbc.Driver");
		ds.setUrl("jdbc:mysql://localhost:3306/websparrow");
		ds.setUsername("root");
		ds.setPassword("");

		return ds;
	}

	@Bean
	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.

StudentController.java
package org.websparrow.controller;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
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;

@Controller
public class StudentController {

	@Autowired
	private StudentDao stuDao;

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

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

		model.addObject("listStu", listStu);
		model.setViewName("index");

		return model;
	}

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

		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.

index.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@page isELIgnored="false"%>
<html>
<body>
	<h2>How to fetch image from database using Spring MVC</h2>


	<table border="1">
		<tr>
			<th>Id</th>
			<th>Name</th>
			<th>Age</th>
			<th>Photo</th>
		</tr>
		<c:forEach var="student" items="${listStu}">
			<tr>
				<td>${student.id}</td>
				<td>${student.name}</td>
				<td>${student.age}</td>
				<td><img width="100" height="100" src="getStudentPhoto/<c:out value='${student.id}'/>"></td>
			</tr>
		</c:forEach>
	</table>

</body>
</html>

Output

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

References

  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.