I want to write image on response stream in JSP Custom tag, can i do that? I've tried at Servlets and its working fine, but in JSP Custom tag in doStartTag() or doEndTag() i have JSPWriter object, using that how can i write image? any idea?
When you say "write it in the response" stream I assume you are saying to return the file (in this case an image) as the response.
There's a pretty good reason why you wouldn't be able to do this in a tag. By the time tag is beginning to process, the response header and part of the body have already been set and you can't change them. You can't suddenly say, "Oh wait, ignore this html stuff I'm sending and just send an image instead!" You'll get an exception if you try.
Is there any reason you are trying to do this other than just experimenting?
I just wanted to show an image on the page on the fly. Don't want to store the image on disk first and then display it through html <img> tag. Want to create image in memory and write its bytes on JSP.
Originally posted by Ali Gohar: I just wanted to show an image on the page on the fly. Don't want to store the image on disk first and then display it through html <img> tag. Want to create image in memory and write its bytes on JSP.
Usually, Image data (i.e. the bytes that make up a gif/jpg or whatever image) is not embedded in an html file. There is a link to an image URL in an HTML page. The browsers requests that image URL separately.
Now, if you want to generate image data from a JSP/Servlet, that's possible (as you have already seen). If you want to generate it from a custom tag, I think it is doable (even though it defeats the purpose of a JSP/Custom tags), but I haven't tried it -
1. The custom tag should be the first and the only data producing tag in the jsp page. For eg.
<@page import...%> <mylib:img params/>
This is to ensure that no text is written to the output.
2. In the doStartTag(), use pageContext().getResponse().getOutputStream(); and then write the bytes to the output stream. I think you should not bother about setting headers etc. at this time. Let the browser figure it out. Usually, browsers do figure out by looking at the datastream what it contains. If it works, try setting appropriate headers such as content type etc.
Please do let us know if it works
Then onLoad() of body, you can use DHTML API (look up at MSDN), and instantiate the image object.
Many charting packages use this method of embedding images in a jsp page.