Including Images with JSP

Example 6-1 illustrates an important detail regarding JSP and images. A common question is “How do I use JSP to include a dynamic image in a page?” The short answer is: you don’t.

First of all, a response can only contain one type of content[1] so you can’t mix HTML and an image in the same response. You may recall from Chapter 2 that a browser handles an HTML response with <img> elements by sending a new request for each image and then merging the HTML and all images. So to include an image in a JSP-generated response, you do the same as you do in a regular HTML page; add an <img> element with the URI for the image. The only difference is that the URI may be decided at runtime, as in Examples Example 6-1 and Example 6-2.

Secondly, JSP is intended for text responses, not binary responses with image bytes. If you need to generate an image dynamically, you should use a servlet instead. In the JSP page, add the <img> element with a URI for the servlet and pass data it may need as request parameters in a query string:

<img src="imageGeneratorServlet?width=100&height=100">

[1] This is true for the general case. An HTTP response can actually contain multiple parts of different types when special headers and delimiters are used, but generating such a response with JSP isn’t recommended.

Get JavaServer Pages, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.