如何让客户端可以下载网页内容

How can i make the content of a webpage downloadable for the client

我正在处理一个项目,但我无法找到一种方法来使从我的数据库中打印出 table 的页面内容可下载。我希望有一个按钮,让客户有机会以 pdf 或 csv 的形式下载 table 的内容。 这是 servlet fo

package bacit.web.bacit_web;

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.sql.*;


@WebServlet(name = "BookingHistorikk", value = "/BookingHistorikk")
public class GetBookingHistorikk extends HttpServlet
{
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
    {
        PrintWriter out = res.getWriter();
        res.setContentType("text/html");
        out.println("<html><body>");
        try
        {
            Class.forName("org.mariadb.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mariadb:**********", "root", "pass");
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("select * from BOOKING");
            out.println("<table style=text-align:center border=1 width=50% height=10% >");
            out.println("<tr><th>Start Dato</th><th>Slutt Dato</th><th>Kommentar</th><th>Levert</th><th>Total Pris</th></tr>");
            while (rs.next())
            {
                Date startDate = rs.getDate("StartDate");
                Date endDate = rs.getDate("EndDate");
                String cmnt = rs.getString("Cmnt");
                Boolean isDelivered = rs.getBoolean("IsDelivered");
                int totalPrice = rs.getInt("TotalPrice");
                out.println("<tr><td>" + startDate + "</td><td>" + endDate + "</td><td>" + cmnt + "</td><td>" + isDelivered + "</td><td>" + totalPrice + "</td></tr>");
            }
            out.println("</table>");
            out.println("</html></body>");
            con.close();
        }
        catch (Exception e)
        {
            out.println("error");
        }
    }
}

这里有两件事你需要做...

  1. 创建 CSV 文件。
  2. HttpServletResponse的帮助下发送给用户。

您可以像这样创建 CSV 文件内容:

String getMyCsvFileAsString() {
    StringBuilder sb = new StringBuilder();
      sb.append("id");
      sb.append(',');
      sb.append("Name");
      sb.append('\n');

      sb.append("1");
      sb.append(',');
      sb.append("Prashant Ghimire");
      sb.append('\n');

      writer.write(sb.toString());
}

然后您可以像这样将其附加到请求中:

public void doGet(HttpServletRequest request, HttpServletResponse response)
{
    response.setContentType("text/csv");
    response.setHeader("Content-Disposition", "attachment; filename=\"myCsvFile.csv\"");
    try
    {
        OutputStream outputStream = response.getOutputStream();
        // Get CSV file as string
        String outputResult = getMyCsvFileAsString();
        
        outputStream.write(outputResult.getBytes());
        outputStream.flush();
        outputStream.close();
    }
    catch(Exception e)
    {
        System.out.println(e.toString());
    }
}