title: How to show a JSP page using Servlet which has image in its Response?
body: <p>Servlet doGet() code for getting an Image from Database and to store image in Response</p>
  
  <pre><code>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)) &gt; 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();
  }
  
  }
  </code></pre>
  
  <p>However, When this servlet shows the JSP page it shows <code>only image</code> and not the JSP page.</p>
  
  <p>JSP code:</p>
  
  <pre><code>... JSP code
  
  &lt;img src="Servlet url"&gt;
  
  ... JSP code cont...
  </code></pre>
  
  <p>What output I get:</p>
  
  <ol>
  <li>I only get Image instead of image inside JSP  </li>
  <li>When I use RequestDispatcher/sendRedirect() I get following Exception <code>java.lang.IllegalStateException: Cannot forward after response has been committed</code></li>
  </ol>
  
  <p>Question:</p>
  
  <ol>
  <li>How to get Image inside JSP instead of just Image in browser</li>
  <li>How to avoid above Exception?</li>
  </ol>
  
  <p>EDIT: My Web.xml looks like this</p>
  
  <pre><code>&lt;servlet&gt;
      &lt;servlet-name&gt;Photo Module&lt;/servlet-name&gt;
      &lt;servlet-class&gt;app.controllers.PhotoServlet&lt;/servlet-class&gt;
  &lt;/servlet&gt;
  &lt;servlet-mapping&gt;
      &lt;servlet-name&gt;Photo Module&lt;/servlet-name&gt;
      &lt;url-pattern&gt;/Photos&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;
  </code></pre>