title: Display image on jsp page through Servlet
body: <p>I am making a small application which uploads a image for authenticated user into database and displays all the images that were previously uploaded dynamically through servlet.</p>
  
  <p>I retrieve images at page load from database using this code:</p>
  
  <pre><code>&lt;head&gt;
  &lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"&gt;
  &lt;jsp:include page="/RetrieveImagesServlet.do"&gt;&lt;/jsp:include&gt;
  &lt;/head&gt;
  </code></pre>
  
  <p>This sets the user images in the page request and is working fine.</p>
  
  <p>Now to display image data in table format i use jstl. Since user image objects contains image in <code>byte[]</code> format so I invoke a servlet to print the image file as below. </p>
  
  <pre><code>&lt;c:forEach var="imageDto" items="${requestScope.userImages}"&gt;
                  &lt;tr&gt;
                      &lt;td&gt;&lt;c:out value="${imageDto.getSerialNumber()}"&gt;&lt;/c:out&gt;&lt;/td&gt;
                      &lt;td&gt;&lt;c:out value="${imageDto.getImageName() }"&gt;&lt;/c:out&gt;&lt;/td&gt;
                      &lt;td&gt;&lt;c:out value="${imageDto.getImageSize()}"&gt;&lt;/c:out&gt;&lt;/td&gt;
                      &lt;td&gt;
                          &lt;c:set var="imageDto" scope="request" value="${imageDto}"&gt;&lt;/c:set&gt;
                          &lt;jsp:include page="/ImageDisplayServlet.do"&gt;&lt;/jsp:include&gt; 
                          &lt;c:remove var="imageDto" scope="request" /&gt;&lt;/td&gt;
                      &lt;td&gt;&lt;/td&gt;
                  &lt;/tr&gt;
              &lt;/c:forEach&gt;
  </code></pre>
  
  <p>The line <code>&lt;jsp:include page="/ImageDisplayServlet.do"&gt;&lt;/jsp:include&gt;</code> included in above code invokes a servlet to display which contains the code below </p>
  
  <pre><code>response.setContentType("image/jpeg");
      final ImageDto imageDto = (ImageDto) request.getAttribute("imageDto");
      System.out.println(imageDto.getImageName());
      final OutputStream outputStream=response.getOutputStream();
      outputStream.write(imageDto.getImageFile());
      outputStream.close();
  </code></pre>
  
  <p>I am able to get the image in invoked servlet as it is able to print the imageName but it throws illegalStateException at <code>final OutputStream outputStream=response.getOutputStream();</code>. </p>
  
  <p>Please guide me where I am wrong and how can I display image on jsp file.</p>