Search code examples
javaservletsdownloaddownload-manager

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


Im working on a project and i cant find a way to make the content of a page that prints out a table from my database downloadable. I want there to be a button that gives the client the opportunity to download the content of the table in form of either pdf or csv. this is the 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");
        }
    }
}

Solution

  • There are 2 things you need to do here ...

    1. Create CSV file.
    2. Send it to the user with the help of HttpServletResponse.

    You can create a CSV file contents like this:

    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());
    }
    

    And then you can attach it to the request like this:

    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());
        }
    }