【问题标题】:Sending text file to client through Spring MVC web application通过 Spring MVC Web 应用程序向客户端发送文本文件
【发布时间】:2015-09-04 14:30:58
【问题描述】:

在对该主题进行了一些在线研究后,我目前设法使用此代码进行处理:

@RequestMapping(value = "/report040Generated", method = RequestMethod.GET)
    public String index(Model model, HttpServletResponse response, HttpServletRequest request) throws IOException {

        String myString = "Hello";
        response.setContentType("text/plain");
        response.setHeader("Content-Disposition","attachment;filename=myFile.txt");
        ServletOutputStream out = response.getOutputStream();
        out.println(myString);
        out.flush();
        out.close();

        return "index";
    }

我的问题是,当我单击 JSP 按钮时,文件会被下载,但该方法不会重定向到“索引”.jsp 视图并给我一个 IllegalStateExcepton:

严重:servlet jsp 的 Servlet.service() 抛出异常 java.lang.IllegalStateException: getOutputStream() 已为此响应调用

关于可能导致此问题的任何建议?

【问题讨论】:

    标签: java spring jsp spring-mvc servlets


    【解决方案1】:

    返回文件时无法重定向到另一个页面,因为文件本身是 http 响应。很好的解释在这里:Spring - download file and redirect

    【讨论】:

      【解决方案2】:

      我认为你程序中的逻辑应该分为两部分,一是下载,一是重定向,因为一旦你写了一些东西到 response # outputstream 属性,响应应该被认为是提交的,不应该被写入,例如使用 url 重定向。

      大多数网站使用首先重定向到下载页面以获取文件,然后让用户单击某个按钮/链接以重定向回任何其他页面(在本例中为 index.jsp)。

      在那个下载页面你可以用JS来做:

      <script type="text/javascipt">
      function startDownload()
      {
      var url='http://server.com/app/url?file=file.ext';  
      window.open(url,'Download');
      }
       
      setTimeout("startDownload(), "2000"); // 2 seconds
      </script>

      或者通过 HTML 试试:

      <html>
      <head>
      <meta http-equiv="refresh" content=".;url=http://server.com/app/url?file=file.ext">
      </head>
      <body>
      Downloading file.zip!
      </body>
      </html>

      【讨论】:

        【解决方案3】:

        在返回“index”之前需要先清除默认的JSPWriter

        out.close(); out.clear(); //clears default JSPWriter return "index";

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-11-18
          • 2011-05-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-10-27
          相关资源
          最近更新 更多