Spring MVC File Download Example (original) (raw)

Hello readers. Spring framework provides an out of box support for the file download functionality from the server to a local machine. In this tutorial, we will show you how to implement the file download functionality with the Spring Mvc framework. To handle the file download capability in a web application, we will use the HttpServletResponse to directly write a file to the ServletOutputStream.

1. Introduction

1.1 Spring Framework

1.1.1 Spring Mvc Framework

Model-View-Controller (Mvc) is a well-known design pattern for designing the GUI based applications. It mainly decouples the business logic from UI by separating the roles of Model, View, and Controller in an application. This pattern divides the application into three components to separate the internal representation of the information from the way it is being presented to the user. The three components are:

Fig. 1: Model View Controller (MVC) Overview

Fig. 1: Model View Controller (MVC) Overview

1.2 Spring Framework’s Support for File Download

Spring Mvc framework provides several approaches for downloading a file in the Spring Mvc web-application. These are:

The following picture depicts the workflow of the sample application we are going to build in this tutorial.

Fig. 2: Spring Mvc File Download Application Workflow

Fig. 2: Spring Mvc File Download Application Workflow

Now, open up the Eclipse Ide and let’s start building the application!

Below are the steps involved in developing this application.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 3: Application Project Structure

Fig. 3: Application Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Fig. 4: Create Maven Project

Fig. 4: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.

Fig. 5: Project Details

Fig. 5: Project Details

Select the Maven Web App Archetype from the list of options and click next.

Fig. 6: Archetype Selection

Fig. 6: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 7: Archetype Parameters

Fig. 7: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

4.0.0 SpringMvcDownloadFile SpringMvcDownloadFile 0.0.1-SNAPSHOT war

We can start adding the dependencies that developers want like Spring Mvc, Servlet Api, MySQL, and Log4j etc. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Database & Table Creation

The following MySQL script is used to create a database called filedownload with table: exam_result. Open the MySQL or the workbench terminal and execute the SQL script:

CREATE DATABASE IF NOT EXISTS filedownload;

USE filedownload;

CREATE TABLE exam_result ( student_id INTEGER NOT NULL, student_name VARCHAR(30) NOT NULL, student_dob DATE NOT NULL, student_percentage double NOT NULL );

INSERT INTO exam_result (student_id, student_name, student_dob, student_percentage) VALUES (101, 'Harry Potter', '1993-02-01', 92); INSERT INTO exam_result (student_id, student_name, student_dob, student_percentage) VALUES (102, 'Java Code Geek', '1987-02-03', 62); INSERT INTO exam_result (student_id, student_name, student_dob, student_percentage) VALUES (103, 'Hermione Granger', '1985-02-01', 76); INSERT INTO exam_result (student_id, student_name, student_dob, student_percentage) VALUES (104, 'Lucifer Morningstar', '1965-02-01', 83);

DESC exam_result;

SELECT * FROM exam_result;

If everything goes well, the database and the table will be shown in the MySQL Workbench.

Fig. 8: Database & Table Creation

Fig. 8: Database & Table Creation

3.2 Maven Dependencies

In this example, we are using the most stable Spring web-mvc, MySQL, and Log4j version in order to set-up the file download functionality. The updated file will have the following code:

pom.xml

4.0.0 SpringMvcDownloadFile SpringMvcDownloadFile war 0.0.1-SNAPSHOT SpringMvcDownloadFile Maven Webapp http://maven.apache.org org.springframework spring-webmvc 4.3.11.RELEASE javax.servlet servlet-api 3.0-alpha-1 javax.servlet jstl 1.2 javax.servlet.jsp jsp-api 2.1 mysql mysql-connector-java 5.1.40 log4j log4j 1.2.17 ${project.artifactId}

3.3 Java Class Creation

Let’s create the required Java files. Right-click on src/main/java folder, New -> Package.

Fig. 9: Java Package Creation

Fig. 9: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.spring.mvc.file.download.

Fig. 10: Java Package Name (com.jcg.spring.mvc.file.download)

Fig. 10: Java Package Name (com.jcg.spring.mvc.file.download)

Once the package is created, we will need to create the implementation class. Right-click on the newly created package, New -> Class.

Fig. 11: Java Class Creation

Fig. 11: Java Class Creation

A new pop window will open and enter the file name as: FileDownloadController. The spring controller class will be created inside the package: com.jcg.spring.mvc.file.download.

Fig. 12: Java Class (FileDownloadController.java)

Fig. 12: Java Class (FileDownloadController.java)

3.3.1 Implementation of Controller Class

This is a typical spring controller class which is annotated by the Spring MVC annotation types. The methods downloadPdf() or the downloadCsv() will receive requests from the client. These two methods will read the file on the server and send it back to the client for downloading. Note that, unlike the traditional spring controller’s methods, these methods do not return a view-name as the application’s purpose is to send a file to the client. The method scope is completed as soon as the file is completely transferred to the client.

Let’s write a quick Java program in the spring controller class to handle the file download requests. Add the following code to it.

FileDownloadController.java

package com.jcg.spring.mvc.file.download;

import java.io.File; import java.io.IOException;

import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView;

@Controller public class FileDownloadController {

static ModelAndView modelViewObj;

private static Logger logger = Logger.getLogger(FileDownloadController.class);

@RequestMapping(value = {"/", "fileDownload"}, method = RequestMethod.GET)
public ModelAndView showUploadFileForm(ModelMap model) {
    modelViewObj = new ModelAndView("fileDownload");
    return  modelViewObj;
}

@RequestMapping(value = "downloadFile/pdf", method = RequestMethod.GET)
public void downloadPdf(HttpServletRequest req,HttpServletResponse resp) throws IOException {
    String pdfFilePath = "", pdfFileName = "irregular-verbs.pdf";
    logger.info("Downloading A .PDF File From The Server ....!");

    /**** Get The Absolute Path Of The File ****/
    pdfFilePath = Util.getFilePath(req) + File.separator + pdfFileName;      
    logger.info("Absolute Path Of The .PDF File Is?= " + pdfFilePath);

    File downloadFile = new File(pdfFilePath);
    if(downloadFile.exists()) {
        Util.downloadFileProperties(req, resp, pdfFilePath, downloadFile);				
    } else {
        logger.info("Requested .PDF File Not Found At The Server ....!");
    }
}

@RequestMapping(value = "downloadFile/csv", method = RequestMethod.GET)
public void downloadCsv(HttpServletRequest req,HttpServletResponse resp) throws IOException {
    String csvFilePath = "";
    logger.info("Downloading A .CSV File From The Server ....!");

    /**** Get The Absolute Path Of The File ****/	
    csvFilePath = GenerateCsvData.writeDbDataToCsvFile(Util.getFilePath(req));		
    logger.info("Absolute Path Of The .CSV File Is?= " + csvFilePath);

    File downloadFile = new File(csvFilePath);
    if(downloadFile.exists()) {
        Util.downloadFileProperties(req, resp, csvFilePath, downloadFile);
    } else {
        logger.info("Requested .CSV File Not Found At The Server ....!");
    }
}

}

3.4 Configuration Files

Let’s write all the configuration files involved in this application.

3.4.1 Spring Configuration File

To configure the spring framework, we need to implement a bean configuration file i.e. spring-servlet.xml which provide an interface between the basic Java class and the outside world. Put this XML file in the SpringMvcDownloadFile/src/main/webapp/WEB-INF folder and add the following code to it:

spring-servlet.xml

<context:component-scan base-package="com.jcg.spring.mvc.file.download" />

error

3.4.2 Web Deployment Descriptor

The web.xml file declares one servlet (i.e. Dispatcher Servlet) to receive all kind of the requests and specifies the default page when accessing the application. Dispatcher servlet here acts as a front controller. Add the following code to it:

web.xml

Spring Mvc File Download Example SpringController org.springframework.web.servlet.DispatcherServlet contextConfigLocation /WEB-INF/spring-servlet.xml 1 SpringController /

3.5 Creating JSP Views

Spring Mvc supports many types of views for different presentation technologies. These include – JSP, HTML, XML etc. So let us write a simple view in SpringMvcDownloadFile /src/main/webapp/WEB-INF/views folder. This page simply shows the download file links which are handled by the methods in the spring controller class (i.e. FileDownloadController.java). Add the following code to it:

fileDownload.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>

Spring Mvc File Download Example

Spring Mvc File Download Example

Download Pdf File
Download Csv File

4. Run the Application

As we are ready for all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server.

Fig. 13: How to Deploy Application on Tomcat

Fig. 13: How to Deploy Application on Tomcat

Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it in the browser.

5. Project Demo

Open your favorite browser and hit the following URL. The output page will be displayed.

http://localhost:8085/SpringMvcDownloadFile/

Server name (localhost) and port (8085) may vary as per your tomcat configuration. Developers can debug the example and see what happens after every step. Enjoy!

Fig. 14: File Download Page

Fig. 14: File Download Page

Click on the download link and the browser will ask to download the particular file.

Fig. 15: Pdf File Download

Fig. 15: Pdf File Download

Fig. 16: Csv File Download

Fig. 16: CSV File Download

That’s all for this post. Happy Learning!!

6. Conclusion

In this section, developers learned how to create a sample Spring Mvc application that allows the file download functionality. Developers can download the sample application as an Eclipse project in the Downloads section, and remember to update the database connection settings.

7. Download the Eclipse Project

This was an example of File Download with Spring Mvc.

Download
You can download the full source code of this example here: SpringMvcDownloadFile