public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // Set the content type res.setContentType("application/pdf"); // Set the content disposition res.setHeader("Content-disposition", "attachment; filename=example.pdf"); // Get the output stream OutputStream out = res.getOutputStream(); // Write binary data to the output stream byte[] data = getData(); out.write(data); out.flush(); out.close(); }
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // Get the output stream OutputStream out = res.getOutputStream(); // Send a string response String response = "Hello World!"; out.write(response.getBytes("UTF-8")); out.flush(); out.close(); }In this example, the doPost() method is used to get the output stream from the response object and send a string response. The string response is converted to bytes using the UTF-8 encoding before being written to the output stream.