有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java通过Spring MVC web应用程序向客户端发送文本文件

在网上做了一些关于这一主题的研究之后,我目前设法使用以下代码:

@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视图,并给我一个非法状态例外:

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

有没有关于导致这个问题的原因的建议


共 (1) 个答案

  1. # 1 楼答案

    我认为程序中的逻辑应该分为两部分,一部分用于下载,另一部分用于重定向,因为一旦您将某个内容写入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>