Spring MVC XML Download
In this demo we will generate XML report using spring MVC and attach in response to the user so that they can open or save on his local system.
To generate report in other format please visit previous tutorial using below link:
Steps for XML report:
- Create maven web project name: SpringMVCDownloadXML below is complete project structure:
- SpringMVCController.java:
package com.javahonk.controller; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class SpringMVCController { @RequestMapping(value = "/downloadXML") public void downloadXML(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/xml"); String reportName = "JavaHonk_XML_Report_.xml"; response.setHeader("Content-disposition", "attachment;filename="+ reportName); ArrayList<String> rows = new ArrayList<String>(); rows.add("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); rows.add("<Details>"); for (int i = 0; i < 4; i++) { rows.add("<Person" + (i + 1) + ">"); rows.add("<FirstName>"); rows.add("Java"); rows.add("</FirstName>"); rows.add("<LastName>"); rows.add("Honk"); rows.add("</LastName>"); rows.add("<Test>"); rows.add("Success"); rows.add("</Test>"); rows.add("</Person" + (i + 1) + ">"); } rows.add("</Details>"); Iterator<String> iter = rows.iterator(); while (iter.hasNext()) { String outputString = (String) iter.next(); response.getOutputStream().print(outputString); } response.getOutputStream().flush(); } }
- index.jsp:
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!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>Spring MVC XML Download Example</title> </head> <body> <form:form action="downloadXML" method="post" id="downloadXML"> <h3>Spring MVC XML Download Example</h3> <input id="submitId" type="submit" value="Downlaod XML"> </form:form> </body> </html>
- We will run this project on tomcat server but you could run on any sever below is output:
- Please visit spring site for more details here
Download Project: SpringMVCDownloadXML