テキストを生成してダウンロードするには、次のようなものを使用できます。
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 );
}
}