getOutputStream() error has already been called for this Response

Asked

Viewed 521 times

1

I have in my application the following error:

getOutputStream() has already been called for this Response.

Ok, the chunk of code that is causing this error is as follows:

boolean hasLogoLogin = new BrandResourceDao().selectByTag(BrandResourceCnt.TAG_BRANDLOGOLOGIN) != null;
boolean hasLogoDefault = new BrandResourceDao().selectByTag(BrandResourceCnt.TAG_BRANDLOGODEFAULT) != null;
boolean hasLogoHight = new BrandResourceDao()
            .selectByTag(BrandResourceCnt.TAG_BRANDLOGOHIGHLIGHTEDE) != null;
boolean hasBackground = new BrandResourceDao().selectByTag(BrandResourceCnt.TAG_BRANDBACKGROUND) != null;

Which is nothing more than a select to check whether the images saved at a certain time in the application really are there. The code just below is repeated for each return of the above selects(Each for its value).

<img id="imgLogoLogin"
    <%=hasLogoLogin
       ? "src='loadImage.jsp?" + Params.TAG + "=" + BrandResourceCnt.TAG_BRANDLOGOLOGIN + "'" : ""%>
style="max-width: 325px; max-height: 200px; width: auto; height: auto;" />

And here the loadImage.jsp that searches the database for the image, converts and displays in the application.

try {
        String tag = request.getParameter(Params.TAG);
        BrandResourceDao dao = new BrandResourceDao();
        BrandResource brand = dao.selectByTag(tag);

if (brand != null) {
   byte[] bytes = Base64.decode(brand.getValue());
   response.setContentType("image/gif");
   OutputStream oImage = response.getOutputStream();  <-- É culpa desse cara aí
   oImage.write(bytes);
   oImage.flush();
   oImage.close();
}
    } catch (Exception e) {
        e.printStackTrace();
    }

Please no swearing by the style of the tag (img) I will put it in css in the future.

Well my doubt is: How to solve this? I need to change the structure is obvious. However I am beginner and do not know how to do it. Does anyone have any ideas to expedite my life with this?

1 answer

1


It is part of the Java API that you can only recover a single output object from the sponse, either through the method getOutputStream or the method getWriter.

If the code in question is within a JSP, you already have one implicit object out which you can use to write the data. Call the method response.getOutputStream not only is it unnecessary as a mistake.

The difference here is that the out is the type PrintWriter, then you’ll have to adapt the code a little bit.

This means that it is not possible to write a byte output from a JSP. I’ve seen implementations that convert bytes to a String and then write the String using out.write(str), but there are cases where there may be loss of information.

The ideal output for your case is not to use a JSP, but to write a Servlet where you can use the getOutputStream duly.

Example (source):

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

       ServletContext cntx= getServletContext();
      // Get the absolute path of the image
      String filename = cntx.getRealPath("Images/button.png");
      // retrieve mimeType dynamically
      String mime = cntx.getMimeType(filename);
      if (mime == null) {
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
      }

      resp.setContentType(mime);
      File file = new File(filename);
      resp.setContentLength((int)file.length());

      FileInputStream in = new FileInputStream(file);
      OutputStream out = resp.getOutputStream();

      // Copy the contents of the file to the output stream
       byte[] buf = new byte[1024];
       int count = 0;
       while ((count = in.read(buf)) >= 0) {
         out.write(buf, 0, count);
      }
    out.close();
    in.close();

}
  • Would you have an example to indicate? Everyone I met is calling getOutputStream().

  • @Cesarrobertomartins I updated the answer with more information

  • Um. . I’m a beginner, as I said, I’ve seen it in several examples of code written the same way. I think it looks good and organized. But I can’t use it. I’m at work, and I’ve been instructed not to use this project model. There is no more "simple" solution in the case of the model I already have here?

  • @Cesarrobertomartins I wish I could go to your company and talk to whoever said that. The official answer is: with JSP I can’t. No one in their right mind does that. Servlets or Controllers (if using any framework) are the right way to do it. The rest is gambiarra. With and I said in the answer, you can try to convert bytes to a String and print this on output, but there is no guarantee that the image will not get corrupted.

  • Anyway, I will communicate this to the project leader and tell him. Let’s see what he has in mind. In the meantime, I’ll solve what I can. Thank you very much for the answer, it was of great help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.