Reading PDF file (binary data) stored in mysql database using servlet & display in browser

In my earlier tutorial, we have seen that how to upload and store PDF file in blob field of MySql database. In continuation to my earlier tutorial, now let us see that how to read PDF file stored in a MySql blob field using servlet and display in a browser.

In this example, let us design an application to read an e-book stored in a database based on the input bookId.

Project structure :

filereadpdf architecture

Step 1: Design a page (fileReadPdf.jsp) to get bookId as input.

The JSP code is given below.

bookReadPdf.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>

<html>
   <head>
        <title>eBook Read</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
<body>
<form  method="get" action="FileReadPdf">
	<table>
	<tr>
	<td>Enter Book Id</td>
	<td>
	<input type="text" name="bookId" />
	</td>
	</tr>
	<tr>
	<td colspan="2">	<input  type="submit"  value="Get Book" /></td></tr>
	</table>
</form>
</body>
</html>

Step 2: Write servlet code to read binary data from the blob field. To read blob field, we can use resultset.getBytes. After reading the blob data, just write it to the response OutputStream so that the binary data can be delivered as PDF in the browser.

The following lines of code is to get the response OutputStream and write the binary data.

ServletOutputStream sos;
sos = response.getOutputStream();
....
sos.write(rset.getBytes("bookcontent"));
..... 

The complete servlet code is given below

FileReadPdf.java

package net.javaonline.servlet.fileupload;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class GetDetails
 */
@WebServlet("/FileReadPdf")
public class FileReadPdf extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileReadPdf() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String bookId = request.getParameter("bookId")!=null?request.getParameter("bookId"):"NA";
		
		ServletOutputStream sos;
		Connection  con=null;
        PreparedStatement pstmt=null;
        
    	response.setContentType("application/pdf");

		response.setHeader("Content-disposition","inline; filename="+bookId+".pdf" );


	     sos = response.getOutputStream();
        

	       try {
	    	   Class.forName("com.mysql.jdbc.Driver");
	    	   con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","j123456");
	      } catch (Exception e) {
	    	  		 System.out.println(e);
	                 System.exit(0); 
	                      }
	       
	      ResultSet rset=null;
			try {
				pstmt = con.prepareStatement("Select bookcontent from Book where bookId=?");
				pstmt.setString(1, bookId.trim());
				rset = pstmt.executeQuery();
				if (rset.next())
					sos.write(rset.getBytes("bookcontent"));
				else
					return;
				
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	
	    sos.flush();
	    sos.close();
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

Now Run the application

http://localhost:8080/TestWeb/fileReadPdf.jsp

filereadpdf

 

Enter book id and click on Get Book

filereadpdf1

 

Now the e-book (pdf file) is opened in the browser.

You may also like

Leave a Reply