You can't1 return both in the same response, since you're returning different types (an HTML page of type text/html
and an image of type image/jpeg
, say).
For this sort of thing, I will generate the image during the initial servlet request (for the containing HTML page). I store it in a cache in my servlet, and write the HTML page with the image tag containing a URL to that image with the handle.
e.g. the browser asks for http://whatever/page
The servlet generates the image, and writes an HTML tag in the page like
<img src="http://whatever/image/unique_handle_to_image">
The browser will render the HTML page, and as part of that issue a new request to my servlet with the handle for the image.
e.g. the browser now asks for http://whatever/image/unique_handle_to_image
I then return the image as content type image/jpeg
or similar.
So you have two requests going on. One for the page, in which you render the image and store it temporarily, and the second in which you return the image. You have to remember to clear the image cache, but that's all straightforward. I wouldn't worry about storing lots of images, since the two requests from the browser usually (!) come in quick succession.
I guess it's possible to use a data uri provided your browser supports it, and create something like
<img src="data:image/png;base64,
iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGP
C/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9YGARc5KB0XV+IA
AAAddEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q72QlbgAAAF1J
REFUGNO9zL0NglAAxPEfdLTs4BZM4DIO4C7OwQg2JoQ9LE1exdlYvBBeZ7jq
ch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0
vr4MkhoXe0rZigAAAABJRU5ErkJggg==" alt="Red dot" />
Note there are a number of caveats surrounding these. See the linked page.