Spring Boot MVC download image or binary file

Sometime we want our user to download some file from our web application that is developed in Spring MVC or Spring Boot. To achieve this the main trick is to send the Content-Disposition http header before sending the data. Here is an example of a Controller class with just one method that take the name of a jpg image file from url, read that file from a predefined location, set the appropriate http header and send the data to the client.

Spring Boot MVC Controller send image or binary data

In web server application, sending image data to client browser is quite common job. This can be easily achieved in Spring or Spring boot MVC Controller. Key things here is to specify proper Content-Type such as image/png or whatever and then return the raw binary data of the image. Here is a sample code to demonstrate the same. @Controller public class ImageController { @RequestMapping("/images/{id}") public ResponseEntity<byte[]> getImage(@PathVariable("id") String id) throws IOException { String filename = "D:/images/" + id + ".

Spring Boot + Spring JPA with PostgreSQL or MySQL or Oracle or SQL Server database and Thymeleaf using Gradle

Here we will see how to build a sample full stack web application using Spring Boot, Spring JPA with database like PostgreSQL, MySQL or Oracle Thymeleaf and Gradle. This example is very similar with my other example regarding Spring boot with H2 database: Spring Boot H2 data source with Thymeleaf using Gradle The only exception here, we will use some production database like postgres as database. So there are changes around Spring JPA configuration and Gradle build file.

Spring Boot run native SQL Query

Here is an example code of how to run native SQL query with parameter in Spring Boot. First we need use Spring boot’s EntityManagerFactory bean. We can simply use @Autowired annotation to make this available in our class. Then create new EntityManager session, run the native SQL and finally close the session. package com.firstfewlines.service; import org.springframework.beans.factory.annotation.Autowired; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.NoResultException; import java.util.Date; public class NativeSqlExample { @Autowired private EntityManagerFactory entityManagerFactory; public Double getDayPrice(String scrip, Date prdate){ EntityManager session = entityManagerFactory.

Spring Boot H2 datasource with Thymeleaf using Gradle

In this example, we will see how to build a simple web application in Spring boot with Thymeleaf as template engine and H2 database as embedded or in-memory database. Gradle has been used as build and dependency management tool. We will create a sample Student Information System where we can enter Student record in one panel and see the existing records in another panel. Here is a screenshot of the web page for this: