0

Servlet doGet() code for getting an Image from Database and to store image in Response

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws 
ServletException, IOException {

// Get userid from session

try {

    // Get photos from database in (image)

    // Init servlet response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setContentType(image.getContenttype());
    response.setHeader("Content-Length", String.valueOf(image.getLength()));
    response.setHeader("Content-Disposition", "inline; filename=\"" + image.getTitle()
    + "\"");

    // Prepare streams.
    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
        // Open streams.
        input = new BufferedInputStream(image.getPhoto(), DEFAULT_BUFFER_SIZE);
        output = new BufferedOutputStream(response.getOutputStream(),
                 DEFAULT_BUFFER_SIZE);

        // Write file contents to response.
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
    } finally {
        // Gently close streams.
        output.close();
        input.close();
    }

    //Redirect it to photo page
    RequestDispatcher rd = request.getRequestDispatcher
        ("/webplugin/jsp/profile/photos.jsp");
    rd.forward(request, response);

} catch (Exception e) {
    e.printStackTrace();
}

}

However, When this servlet shows the JSP page it shows only image and not the JSP page.

JSP code:

... JSP code

<img src="Servlet url">

... JSP code cont...

What output I get:

  1. I only get Image instead of image inside JSP
  2. When I use RequestDispatcher/sendRedirect() I get following Exception java.lang.IllegalStateException: Cannot forward after response has been committed

Question:

  1. How to get Image inside JSP instead of just Image in browser
  2. How to avoid above Exception?

EDIT: My Web.xml looks like this

<servlet>
    <servlet-name>Photo Module</servlet-name>
    <servlet-class>app.controllers.PhotoServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>Photo Module</servlet-name>
    <url-pattern>/Photos</url-pattern>
</servlet-mapping>
a k
  • 797
  • 8
  • 15
  • 24

2 Answers2

4

How to get Image inside JSP instead of just Image in browser

Enter the URL to the JSP file containing the <img> element in the browser address bar.

http://localhost:8080/contextname/webplugin/jsp/profile/photos.jsp


How to avoid above Exception?

Remove the following lines from the servlet code.

//Redirect it to profile page
RequestDispatcher rd = request.getRequestDispatcher
    ("/webplugin/jsp/profile/photos.jsp");
rd.forward(request, response);

The servlet should just return the image. Nothing more. It's the webbrowser itself who is supposed to download and display the image, not the webserver.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • I have removed RequestDispatcher and the Exception is gone and it works fine. But, the Image which should be inside JSP is showing as it is after making your suggested changes. – a k Jun 14 '11 at 18:09
  • 1
    I am confused. What exactly is the problem now? The "But" in your comment namely implies that it doesn't work as you expect, however you also mentioned that it is working fine and that the image is showing as it is. – BalusC Jun 14 '11 at 18:14
  • Also, my web.xml looks as above and I also used `` but still it show only Image in browser and not image inside JSP. – a k Jun 14 '11 at 18:16
  • Then the URL is just plain wrong. Assuming that your JSP indeed runs on `http://localhost:8080/contextname/webplugin/jsp/profile/photos.jsp`, then this `img src` will basically point to `http://localhost:8080/contextname/webplugin/jsp/profile/Photos`, but the servlet actually listens on `http://localhost:8080/contextname/Photos`. As to how to fix that, re-read the answer which I posted in your previous question http://stackoverflow.com/questions/6315671/how-to-retrieve-image-from-database-and-display-in-jsp-via-servlet Yes, you need to prepend the URL with `${pageContext.request.contextPath}`. – BalusC Jun 14 '11 at 18:18
  • My second question about Exception that it was showing is gone and that's working fine. And my First Question about Image is not yet working – a k Jun 14 '11 at 18:19
  • I just used this in my JSP code `` but it still shows just image and not image inside a JSP. – a k Jun 14 '11 at 18:34
  • Did you open the JSP by its address? `http://localhost:8080/contextname/webplugin/jsp/profile/photos.jsp` – BalusC Jun 14 '11 at 18:36
  • No. I am navigating inside through proper anchor tabs – a k Jun 14 '11 at 18:41
  • Does the anchor point to the JSP URL `http://localhost:8080/contextname/webplugin/jsp/profile/photos.jsp`? After all, do you in any way understand that you need to request the JSP URL to see the JSP with the image and NOT alone the image URL? – BalusC Jun 14 '11 at 18:42
  • My photos anchor tag looks like this `">` which i am pressing to call PhotoServlet using web.xml – a k Jun 14 '11 at 18:46
  • The link should point to the URL of the JSP file with the `` not to the URL of the sole image. Fix it accordingly. `">` and so on. Honestly, is that really so hard to understand? – BalusC Jun 14 '11 at 18:50
  • Yeah. Thats working fine. Honestly, I was confused and did all sort of unnecessary things. Glad you helped!!! :) Thank you. – a k Jun 14 '11 at 19:02
  • 1
    Okay. Hopefully you have now also a good understanding what exactly is happening now. The browser requests the JSP. The server executes the JSP which in turn generates and sends a bunch of HTML to the response. The browser retrieves this bunch of HTML code (as you can see when you rightclick page in browser and do *View Source*). The browser parses HTML to display it and encounters a `` and sends a new request on it. Finally the browser displays the image. Using a HTTP traffic checker such as [Firebug](http://getfirebug.com) in *Net* tab should show you all those requests (and responses). – BalusC Jun 14 '11 at 19:08
2

1 you are modifying response and then forwarding , it is useless. don't do it.

2 How to get image from servlet to jsp

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438