Overview
In this tutorial, we show you how to create a simple with Spring 4 MVC to generate Excel file And PDF file with Eclipse Maven, apache poi, itex.Follow the steps mentioned below to develop this application
Watch Tutorial
Project Structure
The following screenshot shows final structure of the project.Create Maven Project
- Launch Eclipse IDE.
- Go to File-> New-> Others... Select Maven Project under Maven category then click Next.
- In New Maven Project wizard, select "Create a simpel project(skip archetype selection)" and click on Next
- In next wizard, type "com.jackrutorial" in the "Group ID:" field
- Type "SpringMvcExportFileExample" in the "Artifact Id:" field
- Packaging -> War
- Click Finish
Maven Dependencies
We specify the dependency for the Spring WebMVC,JSTL, Servlet API, Apache POI, itext . The rest dependencies will be automatically resolved by Maven. The updated pom.xml file will have the following code:<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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jackrutorial</groupId> <artifactId>SpringMvcExportFileExample</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.0.RELEASE</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>com.lowagie</groupId> <artifactId>itext</artifactId> <version>2.1.7</version> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <warSourceDirectory>src/main/webapp</warSourceDirectory> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </pluginManagement> </build> </project>
Configure Web Application
Create the com.jackrutorial.config package.
- Right-click on src/main/java folder, New -> Package
- Enter the package name as: "com.jackrutorial.config"
- Click Finish.
Create a WebConfig class under com.jackrutorial.config package and write the following code in it.
package com.jackrutorial.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @EnableWebMvc @Configuration @ComponentScan(basePackages = { "com.jackrutorial" }) public class WebConfig extends WebMvcConfigurerAdapter{ @Bean public InternalResourceViewResolver viewResolver(){ InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/jsp/"); viewResolver.setSuffix(".jsp"); return viewResolver; } }
Create a WebInitializer class under com.jackrutorial.config package and write the following code in it.
package com.jackrutorial.config; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class[] getRootConfigClasses() { return new Class[] { WebConfig.class}; } @Override protected Class[] getServletConfigClasses() { return null; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } }
Creating Model Layer
Create the com.jackrutorial.model package.
- Right-click on src/main/java folder, New -> Package
- Enter the package name as: "com.jackrutorial.model"
- Click Finish.
Create a User class under package com.jackrutorial.model and write the following code in it.
package com.jackrutorial.model; public class User { private Integer id; private String username; private String firstname; private String lastname; public User() { super(); } public User(Integer id, String username, String firstname, String lastname) { super(); this.id = id; this.username = username; this.firstname = firstname; this.lastname = lastname; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } }
Creating View Layer
Create the com.jackrutorial.view package.
- Right-click on src/main/java folder, New -> Package
- Enter the package name as: "com.jackrutorial.view"
- Click Finish.
Create a ExcelUserListReportView class under package com.jackrutorial.view and write the following code in it.
package com.jackrutorial.view; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.springframework.web.servlet.view.document.AbstractXlsView; import com.jackrutorial.model.User; public class ExcelUserListReportView extends AbstractXlsView { @Override protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setHeader("Content-disposition", "attachment; filename=\"user_list.xls\""); @SuppressWarnings("unchecked") List<User> list = (List<User>) model.get("userList"); Sheet sheet = workbook.createSheet("User List"); Row header = sheet.createRow(0); header.createCell(0).setCellValue("ID"); header.createCell(1).setCellValue("USERNAME"); header.createCell(2).setCellValue("FIRST NAME"); header.createCell(3).setCellValue("LAST NAME"); int rowNum = 1; for(User user : list){ Row row = sheet.createRow(rowNum++); row.createCell(0).setCellValue(user.getId()); row.createCell(1).setCellValue(user.getUsername()); row.createCell(2).setCellValue(user.getFirstname()); row.createCell(3).setCellValue(user.getLastname()); } } }
Create a PdfUserListReportView class under package com.jackrutorial.view and write the following code in it.
package com.jackrutorial.view; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.jackrutorial.model.User; import org.springframework.web.servlet.view.document.AbstractPdfView; import com.lowagie.text.Document; import com.lowagie.text.Table; import com.lowagie.text.pdf.PdfWriter; public class PdfUserListReportView extends AbstractPdfView { @Override protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setHeader("Content-Disposition", "attachment; filename=\"user_list.pdf\""); @SuppressWarnings("unchecked") List<User> list = (List<User>) model.get("userList"); Table table = new Table(4); table.addCell("ID"); table.addCell("USERNAME"); table.addCell("FIRST NAME"); table.addCell("LAST NAME"); for(User user : list){ table.addCell(String.valueOf(user.getId())); table.addCell(user.getUsername()); table.addCell(user.getFirstname()); table.addCell(user.getLastname()); } document.add(table); } }
Creating Controller Layer
Create a ReportController under com.jackrutorial.controller package and write the following code in it.package com.jackrutorial.controller; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.jackrutorial.model.User; import com.jackrutorial.view.ExcelUserListReportView; import com.jackrutorial.view.PdfUserListReportView; @Controller @RequestMapping(value="/") public class ReportController { @RequestMapping(value="/report", method=RequestMethod.GET) public ModelAndView userListReport(HttpServletRequest req, HttpServletResponse res){ String typeReport = req.getParameter("type"); List<User> list = new ArrayList<User>(); list.add(new User(1, "username 1", "First name 1", "Last name 1")); list.add(new User(2, "username 2", "First name 2", "Last name 2")); list.add(new User(3, "username 3", "First name 3", "Last name 3")); list.add(new User(4, "username 4", "First name 4", "Last name 4")); list.add(new User(5, "username 5", "First name 5", "Last name 5")); if(typeReport != null && typeReport.equals("xls")){ return new ModelAndView(new ExcelUserListReportView(), "userList", list); } else if(typeReport != null && typeReport.equals("pdf")){ return new ModelAndView(new PdfUserListReportView(), "userList", list); } return new ModelAndView("userListReport", "userList", list); } }
Creating JSP Views
Create jsp folder under src\main\webapp\WEB-INF\ folder.Create userListReport.jsp file under src\main\webapp\WEB-INF\jsp\ folder and write the following code in it.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Report</title> </head> <body> <table border="1" > <thead> <tr> <td>ID</td> <td>USERNAME</td> <td>FIRST NAME</td> <td>LAST NAME</td> </tr> </thead> <tbody> <c:forEach items="${userList }" var="user" > <tr> <td>${user.id }</td> <td>${user.username }</td> <td>${user.firstname }</td> <td>${user.lastname }</td> </tr> </c:forEach> </tbody> </table> <spring:url value="/report/?type=xls" var="xlsURL" /> <spring:url value="/report/?type=pdf" var="pdfURL" /> <a href="${xlsURL }">Download Excel</a> <a href="${pdfURL }">Download PDF</a> </body> </html>
Configuring Apache Tomcat
Watch video add Apache Tomcat Server in Eclipse IDE.Enter the following to the Host node in the TOMCAT_HOME/conf/server.xml.
<Context docBase="[PROJECT_LOCATION]\SpringMvcExportFileExample\target\SpringMvcExportFileExample-0.0.1-SNAPSHOT\" path="/SpringMvcExportFileExample" reloadable="true" >
Run & Check result
- Start Apache Tomcat from Eclipse IDE.
- Type the following URLs in browser's address bar to open the report page.
http://localhost:8080/SpringMvcExportFileExample/report