• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 297
  • Last Modified:

Retrieve image data from db and show it in browser

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
KNVB HK
Asked:
KNVB HK
  • 17
  • 14
1 Solution
 
OviCommented:
jsp <=> servlet
0
 
KNVB HKSITOAuthor Commented:
I found that there are no jsp example to do so.
0
 
objectsCommented:
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
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
KNVB HKSITOAuthor Commented:
In fact, I got a problem when using response.getOutputStream command.
here is the error message:

java.lang.IllegalStateException
0
 
objectsCommented:
When/why are you calling getOuputStream() ??
Why aren't you simply just writing to the implicit 'out' object?

0
 
KNVB HKSITOAuthor Commented:
Whether out object provide write method?
I need to write a array of data to browser.
0
 
objectsCommented:
Can you post your code.
0
 
KNVB HKSITOAuthor Commented:
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
 
KNVB HKSITOAuthor Commented:
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
 
objectsCommented:
That works becuase you set your content type before you get the output stream.
0
 
KNVB HKSITOAuthor Commented:
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
 
objectsCommented:
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
 
KNVB HKSITOAuthor Commented:
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
 
objectsCommented:
Post the stack trace for the exception.
0
 
KNVB HKSITOAuthor Commented:
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
 
objectsCommented:
Read my comment above again, I don't believe you can call setResponseType() and is causing the exception.
0
 
objectsCommented:
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
 
KNVB HKSITOAuthor Commented:
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
 
objectsCommented:
Why don't you simply use your bean from your servlet?
0
 
KNVB HKSITOAuthor Commented:
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
 
KNVB HKSITOAuthor Commented:
The main reason is that I want to make the servlet can be reuseable.
0
 
objectsCommented:
How is a jsp more reusable than a servlet??
0
 
KNVB HKSITOAuthor Commented:
Sure,To me jsp is no need to compile before use, but servlet ..........
0
 
objectsCommented:
But don't you want to put the logic in a bean (which you'll have to compile)??
0
 
KNVB HKSITOAuthor Commented:
Sure,To me jsp is no need to compile before use, but servlet ..........
0
 
KNVB HKSITOAuthor Commented:
The complexity will be higher.
0
 
objectsCommented:
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
 
KNVB HKSITOAuthor Commented:
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
 
objectsCommented:
What do you need a page for?
All you need is the servlet which returns your image.
0
 
KNVB HKSITOAuthor Commented:
I think you don't understand what I said.
0
 
objectsCommented:
Not sure I did either, can you show me an example to demonstrate?

Thanks for the points :-)
0
 
KNVB HKSITOAuthor Commented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 17
  • 14
Tackle projects and never again get stuck behind a technical roadblock.
Join Now