1

我需要在我的网站上提供一个“文本”文件,以便合作伙伴可以每天阅读数据。我希望动态生成这个“文本”文件。我们为我们的页面使用 JSP 和 Java Servlet

有没有办法在用户访问我的 JSP 或 Java Servlet url 时动态生成要下载的文本文件?

我尝试过使用没有任何 html 的 JSP。它确实在页面上放置了一些文本,但我似乎无法在输出中包含换行符,因此我认为将其作为要下载的文件提供可能会更好。

4

1 回答 1

2

要生成一些文本并下载它,您可以使用以下内容:

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet( name = "TextOutputServlet", urlPatterns = { "/servlets/giveMeSomeText" } )
public class TextOutputServlet extends HttpServlet {

    protected void processRequest( HttpServletRequest request, HttpServletResponse response )
            throws ServletException, IOException {

        response.setContentType( "text/plain;charset=UTF-8" );
        response.setHeader( "Content-Disposition", "attachment;filename=MyTextFile.txt" );
        PrintWriter out = response.getWriter();

        try {

            out.println( "Some content..." );
            out.println( "Some more..." );

        } finally {            
            out.close();
        }

    }

    @Override
    protected void doGet( HttpServletRequest request, HttpServletResponse response )
            throws ServletException, IOException {
        processRequest( request, response );
    }

    @Override
    protected void doPost( HttpServletRequest request, HttpServletResponse response )
            throws ServletException, IOException {
        processRequest( request, response );
    }

}
于 2012-09-18T22:05:45.677 回答