Building 2-D Graphics Applications Using Java and SVG

s Web applications become more sophisticated, developers increasingly need to be able to incorporate dynamic graphics and animation. Unfortunately, Web browsers were originally designed to display static HTML; displaying dynamic or animated content has always been a problem in Web applications.

Nevertheless, solutions exist. One way to display dynamic content is to use Scalable Vector Graphics (SVG), a fairly recent (and still evolving) standard pioneered by Adobe, Sun Microsystems, Apple, IBM, and Kodak. SVG is basically an XML-based representation of graphical commands, used to define complex shapes such as Bezier curves. At SVG’s heart lies the world of vector-based mathematics, hence the name. The beauty of this technology is its minuscule bandwidth consumption as compared to alternatives such as dynamic jpeg file generation using Java and other graphic APIs. SVG also rivals Flash, by providing high-quality panning and zooming.

SVG can be displayed in common Web browsers, although (depending on the browser version) doing so may require a free downloadable SVG plugin from Adobe, called SVG viewer.

Author’s Note: Although other SVG viewers are available, none are even close rivals to the Adobe viewer.

Another great advantage of SVG is that you can integrate it with Java easily. In this article, you’ll see how simple it is to render dynamic graphics for display in Web browsers using SVG with JSPs by exploring how to generate a Pareto chart in SVG.

What You Need
Tomcat, and Adobe’s free SVG Viewer. Even if you’re not planning to work with the sample project, you’ll need to install the viewer to be able to view the SVG examples in this article.

Sample Project Overview

Figure 1. Default View of Logo.svg: This SVG file showcases curves, rectangles, text on a path, and color animation.

The sample project for this article uses a Web-based UI to get user input which it then processes to construct a Pareto chart. Kerri Simon, in this article, writes: “A Pareto chart is used to graphically summarize and display the relative importance of the differences between groups of data.” When the user clicks a “Generate” button on the UI, a JSP page renders the SVG for the chart dynamically. Using similar processing techniques, you can build any type of chart or 2-D image.

If you’re not familiar with SVG, it’s worth starting by viewing a simple SVG file. Install the Adobe SVG viewer, download the sample code, unzip it, and open the logo.svg file in your browser. You’ll see the display shown in Figure 1.

Author’s Note: Based on your browser’s security settings, you may need to give the browser permission to open the SVG. This code has been tested on IE5.5 and above, and on Mozilla Firefox 1.0.4, with the SVG viewer plugin from Adobe installed.

Figure 2. This figure shows the logo.svg file after a user has zoomed into the image using the features added to the browser’s context menu by the SVG plugin.

While Figure 1 shows the default view of the logo.svg file, Figure 2 shows a zoomed view. Note that you get the zoom feature by default?you don’t have to add any special code to the SVG file to provide zooming features.

A Laconic SVG Tutorial
Now that you’ve seen some rendered SVG, here’s how it works. The simplest way to create SVG files is with an SVG editor. There are quite a few SVG editors available today; in my opinion the best is Adobe Go Live. Text in SVG is both selectable and searchable, and can be displayed in any direction?which makes SVG a good choice for displaying text in non-Romanic languages such as Chinese, Japanese, or Arabic. After you familiarize yourself with the viewer plugin features (be sure to explore the right-click menu while viewing the SVG), here’s the code, so you can see how simple it is to read and relate the SVG code to the rendered version.

The quickest way to understand the code is to walk through it. I’ve added extensive comments to the SVG code below that describe the purpose of the various SVG-specific elements:

                                                                                                                              SVG Example                                            SVG                                Java, XML, JSP                                        DevX                           

You can see from the preceding code that SVG is an XML vocabulary. You can change or animate any SVG element easily by making alterations to the base XML file. Because you can draw shapes, add overlay text, lines, and other graphic shapes easily, SVG is an excellent candidate for Web-based mapping and directions applications.

Generating the Dynamic Chart
Now that you’ve seen the output from the application, the more interesting part is how you generate the SVG from a JSP. For brevity and to stick closely to the concept, I embedded the business logic in the SVGController servlet’s service method, rather than using a separate model layer. The application shows how to integrate SVG into the UI generated by the JSP. You can easily extend the same idea to a J2EE app using EJBs.

The application is composed of two JSPs and one servlet as described in the following list:

  • paretoInput.jsp?This creates the UI in which users enter values that affect the generation of the Pareto chart.
    Figure 3. Input Form: This initial page for the Web application lets users enter parameters for the Pareto chart generation.
  • the input values from the submitted form, and processes them to form meaningful information with which to construct the Pareto chart. It then forwards the request to paretoOutput.jsp
  • paretoOutput.jsp?This dynamically outputs the Pareto chart and sets the content type to “SVG.”

To install and run the downloadable sample code, follow these steps. You can use any application server, but the following steps assume you’re running Tomcat.

  1. Create a new Web application called svg_j2ee, or use the war file provided in the sample code.
  2. Copy the source files paretoInput.jsp, SVG Controller and paretoOutput.jsp into the root application folder (svg_j2ee). Alternatively, you can just deploy the war file in your server.
  3. Start the server and browse to http://localhost:8080/pareto/. You’ll see a page similar to Figure 3.
  4. Fill in the input values or accept the default values.
  5. Click the “Generate” button. The server generates the chart and the browser opens it in a new window as shown in Figure 4.
Figure 4. Generated Pareto Chart: The paretoOutput.jsp file generates the chart dynamically, based on input values entered by the user.

A “fat rabbit” is a term used with Pareto charts to identify the root cause of an analysis. Generally it’s the block that is fatter than the rest (in this case, the first one in the chart). In this application, you can choose a different fat rabbit by clicking it with the mouse, which changes the highlighting.

Sample Application Flow
The code is simple and contains comments that should help clarify it. Here’s how the application flows through the three pages.

The application first runs the paretoInput.jsp file, which displays the input UI, asking users to enter parameters used to generate the Pareto chart. This is a standard JSP, with no reference to any SVG; it simply grabs the inputs and passes them on to the SVGController servlet for processing.

The servlet’s service method extracts the request parameters?the headings and values that affect the SVG rendering of the chart. It stuffs these into two vectors, sorts them based on the values, and generates helper vectors for paretoOutput.jsp, that provide percentage and cumulative percentage for graph generation. It then redirects the request, passing all the information required to construct the graph to paretoOutput.jsp as request attributes.

ParetoOutput.jsp sets the content type to “image/svg+xml” to let the browser know that the response content is an SVG file. If the response contains any content that doesn’t adhere to the SVG specification, the SVG plugin will throw an error. Next, it defines the height and width of the SVG display area. The rest of the code is self-explanatory. It is an amalgamation of JSP tags and SVG similar to the code you saw in the logo.svg file on the previous page. The file uses Java variables?passed in just as they are in any JSP?to define the chart values. The code uses those values to generate the Pareto.

It is worth mentioning that you can generate SVG dynamically using other methods such as XSLT. The design requirements of the project should drive your choice of technology. For example, if the application involves transforming XML on the server side for data exchange or for reports then the XSLT approach would make sense, whereas applications without such needs might benefit from the more direct approach described in this article. It’s also worth noting that while this sample application generates a simple chart, SVG is robust enough for use in heavy 2-D graphics applications such as the printed circuit board industry. However, at this stage, SVG’s 3-D capabilities are still somewhat limited.

SVG technology is already mature enough that there are a few books available?and there’s plenty of information on the Web if you want to learn more. The XML representation of SVG opens numerous opportunities for integrating other XML-based technologies. For example, you can use XML-based frameworks such as XUI in conjunction with SVG to provide state-of-the-art visual and interactive capabilities to your Web applications.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


The Latest

6 Web Resources for Coders

6 Online Coding Resources

One of the most rapidly growing job industries today is coding. As more and more of the world moves to a digital format, the demand for skilled coders continues to increase. With a high demand for the skillset, coders tend to be very well compensated for their work. Furthermore, coders

Malware Removal and Protection Software You Should Use in 2023 

The Best Malware Removal Software in 2023

In the modern world, computers are practically a necessity for every home. Computers give us access to vast amounts of information through the internet, as well as provide us with innovative programs and applications like social media, email, and much more. But with these benefits also come the threats of

Why Technology Literacy is So Important for Modern Workers 

Why Technology Literacy is So Important for Modern Workers 

Importance of Having Technology Literacy Today’s world is completely reliant on technological products and advancements. In the current technology-based era, it is crucial to have technology literacy. And these particular instances might be most suitable for the cases of modern workers dealing with modern equipment, especially in the construction sector. 

The Small Business & Data Analytics: What You Need to Know

The Small Business & Data Analytics: What You Need to Know

The objective of any business is to afford its community a product and create extra money for the services provided. Ideally, this always goes as planned, but at times when it doesn’t, having an extra eye on the data analytics of your small business may make a significant difference. Metrics

Break Into Tech Sales in 4 Easy Steps

Break Into Technology Sales in 4 Easy Steps

One of the fastest-growing industries of the 21st century is undoubtedly tech sales. Between innovations like computers, AI, social media, and more, tech is everywhere. And the demand continues to increase. With constant innovations and massive demand, tech sales have become an extremely lucrative industry. As such, there is no