2

Possible Duplicate:
how to display a pdf file in jsp using servlet

I retrieve a pdf file from my database and put it in a file like this

String str="select * from files where name='Security.pdf';";
Statement stmt2= conn.createStatement  
                   (ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs = stmt2.executeQuery(str);
while(rs.next())
{
 InputStream input = rs.getBinaryStream("content");
 //to create file
   File f=new File("c:/pdfile.pdf");
   OutputStream out=new FileOutputStream(f);
   byte buf[]=new byte[1024];
   int len;
   while((len=input.read(buf))>0)
   out.write(buf,0,len);
   out.close();
   input.close();
    System.out.println("\nFile is created..");
}

Now this is at server end. In my client side, Whenever user clicks a link say a href=pdf(pdf is my servlet name) in my jsp page, I should display the file retrieved from database on client's Browser.
What should I do?

Community
  • 1
  • 1
suraj
  • 1,828
  • 12
  • 36
  • 64

2 Answers2

2

Set your content-type of the response to pdf

response.setContentType("application/pdf");

Then write the pdf contents into the response object

ganesshkumar
  • 1,317
  • 1
  • 16
  • 35
2

Don't save the PDF to a file on the server, just send it back to the browser as the servlet's response. Basically, instead of that FileOutputStream, use the OutputStream that you get from calling getOutputStream() on your ServletResponse object. You'll also need to set a Content-Type header so that the browser knows it's a PDF file.

Having a servlet write to a hard-coded path like that is dangerous because several instances of the servlet can run at the same time, in different threads. (Think about what happens if two people enter your servlet's URL in their browsers at the same time.) If they're both writing to the same file at the same time, they'll end up corrupting it.

Wyzard
  • 33,849
  • 3
  • 67
  • 87