Solved

Retrieve image data from db and show it in browser

Posted on 2002-06-05
32
291 Views
Last Modified: 2013-11-23
Is it possible to do this thing without servlet?
I can extract the image data from db and save it to file successfully using jsp only.
0
Comment
Question by:cstsang
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 17
  • 14
32 Comments
 
LVL 9

Expert Comment

by:Ovi
ID: 7055726
jsp <=> servlet
0
 
LVL 7

Author Comment

by:cstsang
ID: 7055755
I found that there are no jsp example to do so.
0
 
LVL 92

Expert Comment

by:objects
ID: 7055761
Sure you can :-)
Just set the content type of the page to be an image:

<%@ page contentType="image/jpeg" %>

Read your image data and write it out same as you would in a servlet.

0
PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

 
LVL 7

Author Comment

by:cstsang
ID: 7055803
In fact, I got a problem when using response.getOutputStream command.
here is the error message:

java.lang.IllegalStateException
0
 
LVL 92

Expert Comment

by:objects
ID: 7055814
When/why are you calling getOuputStream() ??
Why aren't you simply just writing to the implicit 'out' object?

0
 
LVL 7

Author Comment

by:cstsang
ID: 7055844
Whether out object provide write method?
I need to write a array of data to browser.
0
 
LVL 92

Expert Comment

by:objects
ID: 7060566
Can you post your code.
0
 
LVL 7

Author Comment

by:cstsang
ID: 7060765
Here is my code:
<%@page language="java" import="java.io.*"%>
<%
OutputStream outs = response.getOutputStream();
%>

I even got the error message from the above code:

java.lang.IllegalStateException


Can you tell me why?
I am using JRun 3.0 with sp2 +iPlanet web server 4.1+ WinNT 4.0 with SP5+jdk 1.3.1.
0
 
LVL 7

Author Comment

by:cstsang
ID: 7069385
Finally, I only got the result, however, I don't know why.
I build a servlet.Then submit the HTML form to this serlvet.

Then it works, would you tell me why?
Here is my servlet:
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public class BlobHandler extends HttpServlet
{
 private OutputStream os;
 private String fn,sSQL,contentType,JDBC,DBURL,userName,pwd;
 private int bufferSize=1048576,bytesRead=0;
 private byte[] b = new byte[bufferSize];
 private ServletOutputStream sos;
 private InputStream is;
 private int fieldCount=0;
 private ResultSet rs;
 private Connection conn;
 private Statement stmt;
 private int fieldNo;
 private Blob blob;
 private BufferedInputStream bis;
 private BufferedOutputStream bos;
 public void doPost (HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException
 {
   JDBC=request.getParameter("JDBC");
   DBURL=request.getParameter("DBURL");
   userName=request.getParameter("userName");
   pwd=request.getParameter("pwd");
   sSQL=request.getParameter("SQL");
   fn=request.getParameter("fieldCount");
   contentType=request.getParameter("contentType");
   try
      {Class.forName(JDBC);
       conn=DriverManager.getConnection(DBURL,userName,pwd);
       stmt=conn.createStatement();
       rs=stmt.executeQuery(sSQL);rs.next();
       if (contentType==null)
          response.setContentType("image/gif");
       else
          response.setContentType(contentType);
       if (fn==null)
         fieldCount=1;
       else
         fieldCount=Integer.parseInt(fn);  
       blob= rs.getBlob(1);
       is=blob.getBinaryStream();    
       bis=new BufferedInputStream(is,2*bufferSize);
       sos=response.getOutputStream();
       bos=new BufferedOutputStream(sos,2*bufferSize);
       bytesRead=bis.read(b,0,bufferSize);
       while (bytesRead!=-1)
         {
           bos.write(b,0,bytesRead);
           bytesRead=bis.read(b,0,bufferSize);
         }    
       bis.close();
       bos.close();
       is.close();
       sos.close();
       rs.close();
       stmt.close();
       conn.close();
     }
  catch (Exception e)
    {
      response.setContentType("text/html");
      PrintWriter out=response.getWriter();
      out.println("Servlet BlobHandler error occur:"+e.toString());
    }          
 }    
}    

Here is my html form:
<html>
<body>
<form name="test" action="/servlet/BlobHandler" method="post">
  <input type="hidden" name="SQL" value="<%="my_SQL_statement"%>">
  <input type="hidden" name="userName" value="<%=my_db_username%>">
  <input type="hidden" name="pwd" value="<%=db_user_password%>">
  <input type="hidden" name="JDBC" value="<%=JDBCDriver%>">
  <input type="hidden" name="DBURL" value="<%=DBURL%>">
  <input type="hidden" name="fieldCount" value="1">
  <input type="hidden" name="contentType" value="image/gif">
  <input type="submit" value="go">
</form>
</body>
</html>
0
 
LVL 92

Expert Comment

by:objects
ID: 7069435
That works becuase you set your content type before you get the output stream.
0
 
LVL 7

Author Comment

by:cstsang
ID: 7069444
I don't think so. I have changed my jsp program as the following. However, the same error still occur.
<%@page language="java" import="java.io.*"%>
<%
response.setContentType("image/gif");
ServletOutputStream outs = response.getOutputStream();
%>
0
 
LVL 92

Expert Comment

by:objects
ID: 7069465
You're comparing a servlet with a jsp.
You should instead be looking at the servlet generated from your jsp.

The exception you are getting is caused by a header getting set *after* something has been written to the output stream.

I don't think you should be calling the setContentType() method as I think it's already been called (which is probably causing the error). Instead set it as I suggested above.

0
 
LVL 7

Author Comment

by:cstsang
ID: 7069466
I think the main problem is that, Jrun will compile the jsp into servlet first.Then Jrun will execute the servlet.
However, I checked the compiled jsp file(i.e. xxx.java), I found that it alway calls pageContext.getOut() function before calling my program.However, I don't how to tell Jrun to don't place this statement before calling my program.As java doc. said that "pageContext.getOut() cannot be called before calling response.getOutputStream()"
Thus, that why I cannot call response.getOutputStream in my jsp program.

By the way , is there any workaround to deal with this thing?
0
 
LVL 92

Expert Comment

by:objects
ID: 7069470
Post the stack trace for the exception.
0
 
LVL 7

Author Comment

by:cstsang
ID: 7072027
I have changed the program as the following:
<%@page language="java" import="java.io.*"%>
<%
  response.setContentType("image/gif");
  try{
      ServletOutputStream outs = response.getOutputStream();
     }
  catch (Exception e)
     {
      out.print(e);
     }  
%>

the result is :
java.lang.IllegalStateException
0
 
LVL 92

Expert Comment

by:objects
ID: 7072035
Read my comment above again, I don't believe you can call setResponseType() and is causing the exception.
0
 
LVL 92

Expert Comment

by:objects
ID: 7072061
Had a chance to have a closer look at this and it appears I was incorrect and you cannot return binary data from a jsp.
Why exactly don't you want to use a servlet?
0
 
LVL 7

Author Comment

by:cstsang
ID: 7072113
I mean is that if it can done in java bean, then it can give me more flexbility in programming.
Especially, in this case, if it done in java bean,I just pass the resultset object and column no. that store the image to java bean.After the process completed, I can delete the resultset,connection and statement object in my jsp.That mean,I no need to handle the connection and statement object in my java bean.

If I do it in servlet,once I call it then it will not return the control jsp.Therefore, I need to handle the connection and statement object in my servlet.
 
0
 
LVL 92

Expert Comment

by:objects
ID: 7072136
Why don't you simply use your bean from your servlet?
0
 
LVL 7

Author Comment

by:cstsang
ID: 7072138
I mean is that if it can done in java bean, then it can give me more flexbility in programming.
Especially, in this case, if it done in java bean,I just pass the resultset object and column no. that store the image to java bean.After the process completed, I can delete the resultset,connection and statement object in my jsp.That mean,I no need to handle the connection and statement object in my java bean.

If I do it in servlet,once I call it then it will not return the control jsp.Therefore, I need to handle the connection and statement object in my servlet.
 
0
 
LVL 7

Author Comment

by:cstsang
ID: 7072141
The main reason is that I want to make the servlet can be reuseable.
0
 
LVL 92

Expert Comment

by:objects
ID: 7072164
How is a jsp more reusable than a servlet??
0
 
LVL 7

Author Comment

by:cstsang
ID: 7072169
Sure,To me jsp is no need to compile before use, but servlet ..........
0
 
LVL 92

Expert Comment

by:objects
ID: 7072183
But don't you want to put the logic in a bean (which you'll have to compile)??
0
 
LVL 7

Author Comment

by:cstsang
ID: 7072184
Sure,To me jsp is no need to compile before use, but servlet ..........
0
 
LVL 7

Author Comment

by:cstsang
ID: 7072190
The complexity will be higher.
0
 
LVL 92

Expert Comment

by:objects
ID: 7072225
Sorry I don't understand the difference in complexity between calling your image retrieving bean from a servlet and calling it from a jsp.
And you don't have much choice anyway :-)
 
0
 
LVL 7

Author Comment

by:cstsang
ID: 7072244
As I know, there are 2 way pass parameter,1 is submit cgi form and 2 is using session variable
Therefore using serlvet:2 page required
First page content cgi form or session variable initialization.
The second page =the servlet itself.

If it implement in java bean and jsp, 1 page only.
We call the java bean as usual in simple jsp page.
0
 
LVL 92

Accepted Solution

by:
objects earned 105 total points
ID: 7072270
What do you need a page for?
All you need is the servlet which returns your image.
0
 
LVL 7

Author Comment

by:cstsang
ID: 7072289
I think you don't understand what I said.
0
 
LVL 92

Expert Comment

by:objects
ID: 7072321
Not sure I did either, can you show me an example to demonstrate?

Thanks for the points :-)
0
 
LVL 7

Author Comment

by:cstsang
ID: 7074849
Hey Object!That all my code:
The jsp page:
<%@page language="java" import="java.io.*"%>
<%@page language="java" import="java.sql.*"%>
<%@page language="java" import="java.util.*"%>
<%
Class.forName(JDBCDriver);
Connection conn=DriverManager.getConnection(DBURL,username,pwd);
Statement stmt = conn.createStatement();
String sSQL="select wo from wo_data where wono='123'";
ResultSet rs=stmt.executeQuery(sSQL);
session.setAttribute("db_connection",conn);
session.setAttribute("db_stmt",stmt);
session.setAttribute("db_rs",rs);
session.setAttribute("fieldCount",String.valueOf(1));
session.setAttribute("contentType","image/gif");
%>
<html>
<body>
<form name="test" action="/servlet/BlobHandler" method="post">
  <input type="submit" value="go">
</form>
</body>
</html>

Here is the servlet source code:

import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public class BlobHandler extends HttpServlet
{
 private OutputStream os;
 private String fn,contentType;
 private int bufferSize=1048576,bytesRead=0;
 private byte[] b = new byte[bufferSize];
 private ServletOutputStream sos;
 private InputStream is;
 private int fieldCount=0;
 private ResultSet rs;
 private Connection conn;
 private Statement stmt;
 private int fieldNo;
 private Blob blob;
 private BufferedInputStream bis;
 private BufferedOutputStream bos;
 private HttpSession session;
 public void doPost (HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException
 {
  try{
      session=request.getSession();
      fn=(String)session.getAttribute("fieldCount");
      contentType=(String)session.getAttribute("contentType");
      conn=(Connection)session.getAttribute("db_connection");
      stmt=(Statement)session.getAttribute("db_stmt");
      rs=(ResultSet)session.getAttribute("db_rs");
      if (contentType==null)
          response.setContentType("application/pdf");
      else
          response.setContentType(contentType);
      if (fn==null)
         fieldCount=1;
      else
         fieldCount=Integer.parseInt(fn);
      session.removeAttribute("fieldCount");
      session.removeAttribute("contentType");
      session.removeAttribute("db_connection");
      session.removeAttribute("db_stmt");
      session.removeAttribute("db_rs");
      rs.next();
      blob= rs.getBlob(fieldCount);
      is=blob.getBinaryStream();    
      bis=new BufferedInputStream(is,2*bufferSize);
      sos=response.getOutputStream();
      bos=new BufferedOutputStream(sos,2*bufferSize);
      bytesRead=bis.read(b,0,bufferSize);
      while (bytesRead!=-1)
         {
           bos.write(b,0,bytesRead);
           bytesRead=bis.read(b,0,bufferSize);
         }    
      bis.close();
      bos.close();
      is.close();
      sos.close();      
      rs.close();
      stmt.close();
      conn.close();  
     }
  catch (Exception e)
    {
      response.setContentType("text/html");
      PrintWriter out=response.getWriter();
      out.println("Servlet BlobHandler error occur:"+e.toString());
    }          
 }    
}    
0

Featured Post

[Live Webinar] The Cloud Skills Gap

As Cloud technologies come of age, business leaders grapple with the impact it has on their team's skills and the gap associated with the use of a cloud platform.

Join experts from 451 Research and Concerto Cloud Services on July 27th where we will examine fact and fiction.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses

623 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question