You are on page 1of 8

developerWorks : Java : Generating Dynamic XML using JavaServer Pages

IBM Home

Products

Consulting

Industries

News About IBM

Search

IBM : developerWorks : Java overview : Library - papers

Generate dynamic XML using JavaServer Pages technology Use embedded Java code to dynamically build your XML template at request time Marshall Lamb Chief Programmer, WebSphere Transcoding Publisher, IBM December 2000 JavaServer Pages (JSP) technology is typically used for building HTML pages with dynamic content. But you can use this technology to generate dynamic content in other formats as well, including XML. Using real examples, this article will show how to build a JSP page as an XML document template that is "filled in" at request time using Java code embedded in the page.

Contents:

JSP technology overview The mechanics Adding JavaBeans components Conclusion

Web application developers traditionally have used JSP technology to build HTML dynamically by including Java code in the HTML source. But did you Resources know that you can use this same approach to generate dynamic content besides HTML? You can, and it's relatively simple. You can build a JSP page using an About the author XML document that will serve as the template for the output, then replace the portions that must be generated dynamically based on the underlying business logic. You use Java code, either written directly within the JSP page or called externally from the page, to generate the dynamic portions of the document. You are in control of how much of that document is generated. For example, you can use Java code to generate data between XML tags, to generate portions of the XML document tree (both tags and data), or even to generate the entire document. The Java code is removed from the page, processed into a servlet (known as the page servlet) and run by the Java application server as part of the request for the JSP page. The result is pure XML. A JSP technology overview Let's begin by talking a little about how JSP pages work. We're going to keep it simple and focus on some of the basics. For more information, see Resources for links to additional JSP technology information. In the traditional sense, JSP pages look very much like HTML pages, with a few extra tags. These tags allow the designer to embed Java code (not JavaScript) in the page itself. A Web application server, like the IBM WebSphere Application Server, will intercept requests for JSP pages. It's tipped off to their existence by the page's extension: .jsp (not .html). The Web application server then preprocesses the JSP page, taking out the JSP tags and any embedded Java code, leaving only the HTML. The extracted JSP tags and embedded Java code are used to build a Java servlet (JSP page servlet) that runs the code and inserts the results back into the original page where the JSP tags used to be. The result is pure HTML. The Java is stripped out and run on the server before the requesting browser sees any result.

http://www-106.ibm.com/developerworks/library/j-dynxml.html (1 of 8) [1/8/2001 12:39:17 PM]

developerWorks : Java : Generating Dynamic XML using JavaServer Pages

We can apply the same principle to an XML page. Before the requester of the JSP page containing XML ever sees the XML (be it a browser or some other B2B application), the Java code is stripped out of the JSP page and used to generate additional content, which is inserted back into the page at the points where the JSP tags used to reside. This feature gives you the ability to control exactly where new content is to be inserted, down to the character. We'll look at how to make this work in a minute. First, let's consider why you might want to create dynamic XML using JSP. Why not simply write a Java application or servlet to generate the entire document? Why bother with JSP at all? The most important reason, providing only portions of an XML document are dynamic, is that it makes sense not to regenerate that static content for every request. Using a JSP page, the static XML within the page acts as a template that is filled out by the dynamic content. Your Java code is tasked with generating only the content that might change over time -- a more efficient approach. As a practical matter, JSP pages allow you to separate tasks for which different developers will be responsible. In particular, they allow you to better separate the data from the view, allowing you to add new presentations without affecting the logic. Imagine having one Java servlet that performs the business logic and redirects the resulting data to an appropriate JSP page based on the nature of the request. For example, a servlet might redirect data to a JSP page containing WML when it detects a WAP phone browser making the request. It could also redirect the data to a JSP page containing HTML for standard browser requests. The mechanics Let's walk through an example in which a static XML document is converted to a JSP page, and portions of its content are rewritten to be dynamically generated. The example is based on an XML sample shipped as part of the IBM WebSphere Transcoding Publisher called FlightInfo. This XML document represents information about a specific airline flight itinerary. Transcoding Publisher provides it as a sample to show how the product can be used to render the XML data in device-appropriate formats. But before Transcoding Publisher, or any other application, has a chance to manipulate the document, we want to build some of its content dynamically. Here's the original XML document (the DTD has been omitted): <?xml version="1.0" encoding="ISO-8859-1"?> <Flights> <AirCarrier>AA</AirCarrier> <FlightNumber>700</FlightNumber> <FlightSegment> <DepartingInfo> <City>DFW</City> <Date>30Mar</Date> <Scheduled>0630A</Scheduled> <Status>ON TIME</Status> <Time>0632A</Time> <Gate>C16</Gate> <OffGateTime>0644A</OffGateTime> D5</Gate> <Baggage>B</Baggage> <OnGroundTime>1043A</OnGroundTime>
http://www-106.ibm.com/developerworks/library/j-dynxml.html (2 of 8) [1/8/2001 12:39:17 PM]

developerWorks : Java : Generating Dynamic XML using JavaServer Pages

</ArrivingInfo> </FlightSegment> </Flights> Rename the file using a .jsp extension First, we need to rename the file with a .jsp extension so that the Web server will know what to do with the file. Web servers have rules for acting on certain URL patterns or file extensions, such as .html or .gif. When a Web application server is added to a Web server, the application server adds rules to the Web server's list for handling URLs and file extensions specific to the application server. When a Web server sees a file with a .jsp extension, it will pass that request on to the Web application server for processing. Add the page directive Next, we need to indicate to the JSP page compiler what the format of the generated content will be. By default, the page compiler will assume the content is HTML. To override this, a JSP page directive tag must be added to set the content type. For JSP 1.0, the content type page directive looks like this: <%@ page contentType="text/xml;charset=ISO-8859-1" %> It's important to note that the JSP page compiler will remove only the characters making up the tag and its contents. If you place a JSP tag on a new line, the page compiler will remove everything but the new line (because that is not part of the tag). For example, suppose we add the content type tag to our new JSP page like so: <%@ page contentType="text/xml;charset=ISO-8859-1" %> <?xml version="1.0" encoding="ISO-8859-1"?> <Flights> <AirCarrier>AA</AirCarrier> <FlightNumber>700</FlightNumber> <FlightSegment> ... In this case, the page compiler will remove the page directive on the first line, leaving a blank line before the <?xml...?> version tag. In XML documents, the XML version tag must be on the first line, so this example would cause an error in an XML parser. To remedy this, add the page directive to the second line, or concatenate the XML version tag with the content tag. It really doesn't matter where in the document the page directive is placed because the page compiler will add the instruction to the beginning of the resulting page servlet's service() method regardless of its placement in the page. For readability, though, you may want to consider adding it as the second line, like this: <?xml version="1.0" encoding="ISO-8859-1"?> <%@ page contentType="text/xml;charset=ISO-8859-1" %> <Flights> <AirCarrier>AA</AirCarrier> <FlightNumber>700</FlightNumber> <FlightSegment> ...

http://www-106.ibm.com/developerworks/library/j-dynxml.html (3 of 8) [1/8/2001 12:39:17 PM]

developerWorks : Java : Generating Dynamic XML using JavaServer Pages

Add the Java code Now all that is left is to add the Java code to customize some of the content of the XML. We add the Java code to the file between scriptlet tags (<%...%>). The page compiler will interpret anything between these tags as pure Java code and will add it, unchanged, to the service() method of the resulting page servlet. All code within the scriptlet tags is added to the service() method in the order that it appears within the JSP page. The scope of the code added is the entire page, and thus the entire service() method. So if you define a variable in one set of scriptlet tags at the beginning of the file, you can reference it later in the file using a completely different set of scriptlet tags. You can impose a scope by adding your own sets of curly braces ({...}) around variable definitions. These braces can even begin and end in different sets of scriptlet tags. In the following example, I replace a few of the static dates in the original XML file with some Java code using the Calendar class. The code uses the current date and adds hours and minutes along the way to create the appropriate time entries for several of the XML tags. The Java code is boldfaced. Line numbers are added for reference later. 1. <?xml version="1.0" encoding="ISO-8859-1"?> 2. <%@ page contentType="text/xml;charset=ISO-8859-1" %> 3. <% java.util.Calendar cal = java.util.Calendar.getInstance(); %> 4. <Flights> 5. <AirCarrier>AA</AirCarrier> 6. <FlightNumber>700</FlightNumber> 7. <FlightSegment> 8. <DepartingInfo> 9. <City>DFW</City> 10. <Date>30Mar</Date> 11. <Scheduled> 12. <% out.print(cal.getTime().toString()); %> 13. </Scheduled> 14. <Status>ON TIME</Status> 15. <% cal.add(java.util.Calendar.MINUTE, 10); 16. out.print("<Time>" + cal.getTime().toString() + 17. "</Time>"); %> 18. <Gate>C16</Gate> 19. <OffGateTime>0644A</OffGateTime> 20. <OffGroundTime>0632A</OffGroundTime> 21. </DepartingInfo> 22. <ArrivingInfo> 23. <City>LGA</City> 24. <Date>30Mar</Date> 25. <Scheduled> 26. <% cal.add(java.util.Calendar.HOUR_OF_DAY, 4); 27. out.print(cal.getTime().toString()); 28. cal.add(java.util.Calendar.MINUTE, 2); %> 29. </Scheduled> 30. <Status>ON TIME</Status>
http://www-106.ibm.com/developerworks/library/j-dynxml.html (4 of 8) [1/8/2001 12:39:17 PM]

developerWorks : Java : Generating Dynamic XML using JavaServer Pages

31. <Time><%= cal.getTime().toString() %></Time> 32. <Gate>D5</Gate> 33. <Baggage>B</Baggage> 34. <OnGroundTime>1043A</OnGroundTime> 35. </ArrivingInfo> 36. </FlightSegment> 37.</Flights> Here's what's happening in this code segment: Line 2: The page directive is added to indicate that the response generated by the page servlet will contain XML. Line 3: The Calendar variable cal is defined to contain the current date and time. Line 12: Using the global out object, we can print directly into the current position of the page being sent as the response. We print the current time stamp back into the page. Note that when the response is generated, the JSP scriptlet tags will be replaced with the time stamp result. Lines 15-17: We add 10 minutes to the current time and print the result to the page as the departure time. Lines 26-28: We add 4 hours to the current time to derive the scheduled arrival time of the flight, which is then printed to the page using the out object. Afterwards, we add another 2 minutes to create the actual arrival time. Line 31: The equals sign with the scriptlet tags (<%=...%>) will cause the result of anything contained within the tags to be printed to the page. The line in the example is equivalent to the following line using the standard scriptlet tag: <% out.print(cal.getTime().toString()); %> Note that the cal object is global to the entire page, even though it is used in a different set of scriptlet tags from where it is defined. As I mentioned before, unless you add braces ({...}) to enforce scope, variable declarations are global to the entire page from the point of declaration. Also, the Java code in this example is used primarily to generate data between XML tags. We could also use Java code to generate entire trees of tags in an XML document. The code must simply print out the tags in addition to the data. This is what lines 15-17 do. Adding JavaBeans components The JSP syntax supports adding JavaBeans components to the page and accessing them like any other Java object. The special <jsp:useBean> tag is used to declare and instantiate the bean. The page compiler will use the attributes of the <jsp:useBean> tag to build the Java code in the page servlet, which is necessary to instantiate the bean and populate it with data from the request. Because JavaBeans components are generically meant to perform a task, it's easy to see how they can be used to perform or interface with complex business logic, moving the complex Java code out of the JSP page. One example is an Integration Object JavaBean component. This bean was built using IBM WebSphere Host Publisher, which encapsulates interactions with legacy data sources, such as 3270 applications or databases, and simply returns their data. Imagine using an Integration Object that interfaces with a host-based airline scheduling application to provide the arrival and departure
http://www-106.ibm.com/developerworks/library/j-dynxml.html (5 of 8) [1/8/2001 12:39:17 PM]

developerWorks : Java : Generating Dynamic XML using JavaServer Pages

information in our example. As a user of the Integration Object, you simply request the itinerary data from it, unaware of the complex communication and interactions with the host application that occur in the background. Here's our example rewritten to use such a bean. 1. <?xml version="1.0" encoding="ISO-8859-1"?> 2. <%@ page contentType="text/xml;charset=ISO-8859-1" %> 3. <jsp:useBean id="flightInfo" class="IntegrationObject.FlightInfo"/> 4. <% flightInfo.doHPTransaction(request, response); %> 5. <Flights> 6. <AirCarrier>AA</AirCarrier> 7. <FlightNumber>700</FlightNumber> 8. <FlightSegment> 9. <DepartingInfo> 10. <City>DFW</City> 11. <Date>30Mar</Date> 12. <Scheduled> 13. <% out.print(flightInfo.getScheduledDeparture()); %> 14. </Scheduled> 15. <Status>ON TIME</Status> 16. <% out.print("<Time>" + flightInfo.getActualDeparture() + \ 17. "</Time>"); %> 18. <Gate>C16</Gate> 19. <OffGateTime>0644A</OffGateTime> 20. <OffGroundTime>0632A</OffGroundTime> 21. </DepartingInfo> 22. <ArrivingInfo> 23. <City>LGA</City> 24. <Date>30Mar</Date> 25. <Scheduled><%= flightInfo.getScheduledArrival() %> 26. </Scheduled> 27. <Status>ON TIME</Status> 28. <Time><%= flightInfo.getActualArrival() %></Time> 29. <Gate>D5</Gate> 30. <Baggage>B</Baggage> 31. <OnGroundTime>1043A</OnGroundTime> 32. </ArrivingInfo> 33. </FlightSegment> 34.</Flights> Let's take a closer look at what's going on in this sample. Line 3 contains the <jsp:useBean> tag that defines and instantiates the bean IntegrationObject.FlightInfo as flightInfo. The next line contains a scriptlet that calls the doHPTransaction() method of flightInfo, causing it to connect to the host flight information application and retrieve pertinent flight information. Lines 13, 16, 25, and 28 simply insert the results back into the XML document.

http://www-106.ibm.com/developerworks/library/j-dynxml.html (6 of 8) [1/8/2001 12:39:17 PM]

developerWorks : Java : Generating Dynamic XML using JavaServer Pages

You can use other types of beans in exactly the same manner, perhaps calling some other invocation method besides doHPTransaction() to do the work. You can even add multiple beans to the same document, creating a composite XML view of data from multiple sources. Conclusion JavaServer Pages technology has been an open standard for several years and has been widely used for generating dynamic HTML documents. Few have realized that the same flexibility of embedding actual Java code within an HTML document can be applied to generating XML. Consider the possibilities. You could streamline B2B communications by dynamically building only the data that changes. You might build various representations of data from one data source, not just HTML and XML, but WML and HDML for wireless protocols, or simply use products like WebSphere Transcoding Publisher to convert your dynamic XML to device-appropriate representations. XML clearly has been embraced as the common format for data interchange. Using JavaServer Pages technology provides a powerful tool for sending your data over the Web in XML quickly and easily. Resources q Sun Microsystem's definitive reference gives information on how to use JavaServer Pages technology. q The developerWorks XML zone offers technical papers and articles on XML basics and the latest in XML developments. q Find links to technical presentations, documentation, and downloads at these IBM Web sites: r The IBM WebSphere Application Server product page
r r

The IBM WebSphere Host Publisher product page The IBM WebSphere Transcoding Publisher product page

About the author Marshall Lamb is a senior software engineer in the Application and Integration Middleware division at IBM in Research Triangle Park, NC. He's been with IBM for nine years and has a B.S. in Math and Computer Science from Vanderbilt University. He was the chief programmer for the 2.1 release of Host Publisher and is now chief programmer for the WebSphere Transcoding Publisher project. His developerWorks article on implementing JavaHelp is based on his Host Publisher experience. You can contact Marshall at mlamb@us.ibm.com.

What do you think of this article? Killer! (5) Comments? Good stuff (4) So-so; not bad (3) Needs work (2) Lame! (1)

Submit feedback

http://www-106.ibm.com/developerworks/library/j-dynxml.html (7 of 8) [1/8/2001 12:39:17 PM]

developerWorks : Java : Generating Dynamic XML using JavaServer Pages

Privacy Legal

Contact

http://www-106.ibm.com/developerworks/library/j-dynxml.html (8 of 8) [1/8/2001 12:39:17 PM]

You might also like