Java Mailing List Archive

http://www.junlu.com/

Home » Home (12/2007) » Struts 2 »

Re: read/display image from Database using struts

Dariusz Wojtas

2006-12-18

Replies:

On 12/18/06, Kranti <kranti.j2ee@(protected):
> Dear Dariusz ,
>
> this is the first time for me to solve this kind of problem.
> could you provide some sample code to address this.
>
> thanks in advance


This is something simplified, may not compile - but exactly shows what
needs to be done.
Passing of blobID may be done in many ways, this way gives you chance
to pass nice URLs without questionmarks, etc.
Something of type
  /dbImg/123456.jpg
  /dbImg/123456.png
etc.

Dariusz Wojtas


public class MyBlobImageServlet extends HttpServlet {
  public static final long EXPIRY_PERIOD = 60 * 60 * 1000;  // one
hour, depends on your needs

  @Override
  protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
    String pathInfo = request.getPathInfo();
    String blobID = calculateBlobID(pathInfo);
    if (blobID == null) {
       // write some debug if needed
       return;
    }

    byte[] imageData = getBlobFromDB(BlobID);
    if (imageData == null) {
       // write some debug if needed
       return;
    }

    long lastModified = ... // depends on the logic, may be
System.currentTimeMillis()

    // set response headers
    response.setContentLength(imageData.length);
    response.setContentType("image/png");  // depends on your
actual blob content, may vary
    response.setDateHeader("Last-Modified", lastModified);
    response.setDateHeader("Expires", lastModified + EXPIRY_PERIOD);


    // send the image to the browser
    try {
       response.getOutputStream().write(imageData);
    } catch (Exception e) {
       // write stacktrace, maybe some more info (request params, etc.)
    }
  }
}


------------
web.xml

Define servlet, then mapping to it.

  <servlet>
    <servlet-name>blobImageServlet</servlet-name>
    <servlet-class>my.package.MyBlobImageServlet</servlet-class>
  </servlet>


  <servlet-mapping>
    <servlet-name>blobImageServlet</servlet-name>
    <url-pattern>/dbImg/*</url-pattern>
  </servlet-mapping>

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@(protected)
For additional commands, e-mail: user-help@(protected)

©2008 junlu.com - Jax Systems, LLC, U.S.A.