Using SVG in Servlets and JavaServer Pages
The Scalable Vector Graphics (SVG) is a language used for creating vector (as opposed to raster) graphics, including shapes, images, and text. Since this format is based on the extensible markup language (XML), it can be extremely useful in web page authoring.
But the problem is that most of the current browsers do not have built-in support for SVG. Currently, this support is added through plug-ins, e.g. the Adobe SVG viewer. I don't know what percentage of internet users have installed an SVG plug-in. So it seems that if we are going to use SVG in our web pages in a practical way, we must rasterize the image before sending the page to the client (though this makes it an ordinary image, not a vector graphic!).
This can be easily done in JSP pages using the library of the Apache Batik project. I have done this and I present the code below. (Please note that the code for this post is released under the GNU General Public License and that there is no warranty as to its correctness or usability.)
Conversion of the SVG source into an image in PNG format may make problems in a case of simultaneous access. So, a
noCache attribute has been devised for the
<h:svg> tag, so that we can turn on/off the conversion. The best way would be to use
noCache="true" while the page is under development, and then turn off conversion with
noCache="false" when our images have taken their permanent form.
The full source of my simple application (
svgtest) is shown below. But please keep in mind that you need the following libraries to get this application running:
- Batik jar file(s) (may be a single or multiple jar files depending on your build target). I have used batik 1.5.
- JSTL (
- Xerces XML parser (
xerces_2_3_0.jar). This is included with the batik distribution linked above.
Needless to say, the jar files go to the
|Figure 1. The graphics on this page have been created using SVG. Particularly, the three hiragana and kanji characters comprising the Japanese phrase for "Good day!" (今日は) (konnichi wa in rōmaji) have been rendered graphically to ensure their proper appearance even on machines lacking suitable unicode fonts.|
The source code for this simple application follows.
The better way to do this is to write a servlet that outputs the image stream to the client. This will not envolve the writing of the image on disk. Even we can map files with
.svg extension to that servlet, so that whenever we reference an SVG file on our application in the
src attribute of an
<img> tag, the servelt will be activated and the rasterized image will be sent instead. On the other hand, the JSP architecture seems to be inconvenient for outputting binary formats.