Spring MVC 中的 XML 文件下载

标签 xml spring download

我需要通过 spring mvc 下载 xml 文件,并需要我的应用程序在使用 ModelAndView 成功下载后导航到另一个 jsp 页面。下载文件时出现错误

java.lang.IllegalStateException: getOutputStream() has already been called for this response

您能帮我解决这个问题吗?

@RequestMapping(value="/download",method = RequestMethod.GET)
public ModelAndView downloadXmlFile(HttpServletRequest request,
        HttpServletResponse response) throws IOException {

   servletcontext context = request.getsession().getservletcontext()

    File downloadFile = new File("c:\\abc.xml");
    FileInputStream inputStream = new FileInputStream(downloadFile);

    // get MIME type of the file
    String mimeType = context.getMimeType(fullPath);
    if (mimeType == null) {
        // set to binary type if MIME mapping not found
        mimeType = "application/octet-stream";
    }
    System.out.println("MIME type: " + mimeType);

    // set content attributes for the response
    response.setContentType(mimeType);
    response.setContentLength((int) downloadFile.length());

    // set headers for the response
    String headerKey = "Content-Disposition";
    String headerValue = String.format("attachment; filename=\"%s\"",
            downloadFile.getName());
    response.setHeader(headerKey, headerValue);

    // get output stream of the response
    OutputStream outStream = response.getOutputStream();

    byte[] buffer = new byte[4096];
    int bytesRead = -1;

    // write bytes read from the input stream into the output stream
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, bytesRead);
    }

    inputStream.close();
    outStream.close();

    return "Success";
}

最佳答案

  1. Create a Pojo Class Employee
import java.io.Serializable;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Book implements Serializable {

String title;
int pages;
String isbn;

public String getTitle() {
    return title;
}

@XmlElement
public void setTitle(String title) {
    this.title = title;
}

public int getPages() {
    return pages;
}

@XmlElement
public void setPages(int pages) {
    this.pages = pages;
}

public String getIsbn() {
    return isbn;
}

@XmlElement
public void setIsbn(String isbn) {
    this.isbn = isbn;
}

}
  1. Create a Controller
import java.io.IOException;
import java.io.ObjectOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

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, JAXBException {
    Book book = new Book();
    book.setTitle("Lord of the Rings");
    book.setIsbn("Abbbbbb112");
    book.setPages(400);

    try {

        response.setContentType("application/xml");
        response.setHeader("Content-Disposition",
                "attachment; filename=somefile.xml");

        JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        // writing to a file
        /*ObjectOutputStream out = new ObjectOutputStream(
                response.getOutputStream());*/
        jaxbMarshaller.marshal(book, response.getOutputStream());
        // writing to console
        // jaxbMarshaller.marshal(book, System.out);
        response.flushBuffer();
    } catch (Exception e) {
        e.printStackTrace();
    }

   }

  }


    > 3. **Create a Jsp 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>



    > # Header 1 # 4. Create web.xml 
  <?xml version="1.0" encoding="UTF-8"?>
  <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns="http://java.sun.com/xml/ns/javaee"    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
  <servlet-name>dispatcher</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
 </servlet-mapping>
 <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
  </context-param>
  <listener>
 <listener-  class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 </web-app>


> 5. Create dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans     
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd">

 <context:component-scan base-package="com.javahonk.controller" />
 <mvc:annotation-driven/>    

</beans>

** 给出基础包名称**

当我们不使用response.flushBuffer()时,有时它不会写入内容

关于Spring MVC 中的 XML 文件下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18680336/

相关文章:

javascript - 在客户端系统中使用客户端脚本的文件下载选项

php - 使用 htaccess 强制下载图像

java - android.os.TransactionTooLargeException 检索已安装的应用程序

sql-server - 禁止重复列的 XML DML (Xpath) 查询。它应该在插入列之前测试它是否存在

java - 限制每个资源的最大文件大小

java - tomcat 4节点中的ehcache实现

javascript - 网页上的图像 map 是否存在性能问题

c# - XmlSerializer 在序列化时忽略属性覆盖

android - 保存图像缩放后查看

java - 无法解析对 bean 'sessionFactory' 的引用