Article

Consume XML In JSP

Page: 1 2 3 4

Writing the Tag

Writing the tag should now be fairly simple. We need to pick up the following attributes from the designer:

  • the URL to the XML source
  • the code for the company (let's use CSW, the friendly name for my mythical company - Clearly Something Wrong Company Ltd)
  • the attribute name under which we would like the result stored

The tag doesn't need to have any body content, so I implement TagSupport.

Straight off, that gives us:

package com.clearlysomethingwrong;    
   
import javax.servlet.http.HttpServletRequest;    
import javax.servlet.jsp.tagext.TagSupport;    
import javax.servlet.jsp.tagext.Tag;    
import javax.servlet.jsp.JspException;    
   
import org.xml.sax.SAXException;    
import javax.xml.parsers.ParserConfigurationException;    
import java.io.IOException;    
import java.net.URL;    
   
public class ShowSharePrices extends TagSupport {    
   public String investorURL;    
   public String code;    
   public String friendlyName;    
   public String attName;

First, we get the request. We're going to store the attribute here, so we'll need it. In the real application, we could also check that all the values are valid and have been supplied in a meaningful way to provide the user (of the tag, and of the system) with useful error messages. We create a URL object with the given URL string. This URL object simply gives us access to a URL, including providing a number of details about it, and opening an InputStream to it.

Provided the contents of the URL are what we want, this value can then be passed to our investor information loader, together with the code that will extract the appropriate share details and the optional user-friendly name for our company.

If the result is not NULL, we set the attribute using the given attribute name, and exit:

   public int doStartTag() throws JspException {    
       HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();    
       InvestorInformation info = null;    
   
       try{    
   
         URL url = new URL(investorURL);    
         info = InvestorInfoLoader.loadInvestorInfo(url.openStream(),    
                                    code, friendlyName);    
   
       } catch(IOException e) {    
           throw new JspException("Error reading XML source");    
   
       } catch (SAXException e) {    
           throw new JspException("Sax exception occurred: " + e.getMessage());    
   
       } catch (ParserConfigurationException e) {    
           throw new JspException("Configuration error:" + e.getMessage());    
   
       }    
   
       if(info!=null) {    
           request.setAttribute(attName, info);    
       }    
       return Tag.SKIP_BODY;    
   }

Except for the self-evident mutators and accessors, we can now create the tag library descriptor:

<?xml version="1.0" encoding="ISO-8859-1" ?>    
<!DOCTYPE taglib    
 PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"    
 "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">    
   
<taglib>    
   
 <tlib-version>1.0</tlib-version>    
 <jsp-version>1.2</jsp-version>    
 <short-name>xmlInvestor</short-name>    
 <uri>/xmlInvestor</uri>    
 <description>    
   Investor Information Loader Tag    
 </description>    
   
 <tag>    
   <name>loader</name>    
   <tag-class>InvestorInfoLoader</tag-class>    
   <body-content>empty</body-content>    
   <description>    
     Loads investor information given a URL of the XML source, a company investor code, and an attribute name to    
 store the resultant InvestorInformation class. Optionally, a friendly name can be provided for the company.    
   </description>    
       
   <attribute>    
     <name>investorURL</name>    
     <required>true</required>    
     <rtexprvalue>false</rtexprvalue>    
   </attribute>        
   
   <attribute>    
     <name>code</name>    
     <required>true</required>    
     <rtexprvalue>false</rtexprvalue>    
   </attribute>        
   
   <attribute>    
     <name>attName</name>    
     <required>true</required>    
     <rtexprvalue>false</rtexprvalue>    
   </attribute>        
   
   <attribute>    
     <name>friendlyName</name>    
     <required>false</required>    
     <rtexprvalue>false</rtexprvalue>    
   </attribute>        
   
 </tag>    
</taglib>

When packaged according to the standard JSP Tag requirements, using the tag is as simple as giving the following JSP file:

<%@ page import="com.clearlysomethingwrong.InvestorInformation"%>    
<%@ taglib uri="/xmlInvestor" prefix="xmlInvestor"%>    
   
<xmlInvestor:loader  friendlyName="Something Clearly Wrong"    
               code="CSW" attName="InvestInfo"    
               investorURL="http://localhost:8080/source.xml"/>    
<%    
 InvestorInformation info = (InvestorInformation)request.getAttribute("InvestInfo");    
 if(info!=null) {    
   %><%=info.getName()%><br>    
   <%=info.getCurrentPrice()%><br>    
     <%=info.getChange()%><br>        
     <%=info.getTime()%><br>        
     <%=info.getFormattedDate()%><br>    
     <%=info.getPercentage()%><br>        
<%    
 }    
%>

The only possible complaint might be the lack of use of another tag or set of tags for outputting the data, however, I’ve found that tags still confuse programs like Dreamweaver.

The scripts are basically provided because Dreamweaver tends to deal more gracefully with them than tags it doesn’t know about. A significant amount of support is required to write the plug-in that will prevent the average designer wrecking the code when redesign is necessary.

A Note About Outputting XML In JSP

It is my opinion that, unless the project warrants serious investment in software development that’s not core to the average Web developer, writing complex code to output XML using DOM in a JSP based application is counter-productive, and introduces expensive maintenance requirements.

On the whole, where a reasonably flat structure is all that’s needed, the intuitive approach to providing XML output is to merely copy the format of the document into a JSP page and insert scriptlets that will insert the necessary data.

The document we’ve just designed to provide share information would look like this:

<shares>    
 <share>    
   <code><%=info.getName()%></code>    
   <price><%=info.getPrice()%></price>    
         ... etc    
 </share>    
</shares>

In many cases, this has saved a great deal of time, is very easy to check (because loading it into Internet Explorer will also check its validity), and does the job nicely.

To Run This Code

My primary development environment is J2SDK1.4, in which XML processing is included as standard. Those on JDK1.3 will need to download the XML pack available from http://java.sun.com/. Otherwise, the code includes only standard java classes.

To make it easy for you to run the code, I've packaged the Tag in a jar file according to the JSP tag specifications. This makes for a very simple way of including the functionality provided by the tag in a JSP file. Merely drop the jar file in the lib directory within WEB-INF. I recommend you spend some time to learn this simple method, as it can save the usual configuration rush at the end of a project, and is more reusable.

Conclusion

The code is quite straightforward, but this is as it should be, if possible. Each class is quite simple and nicely encapsulates its role without too much overlap in roles.

The most important thing is the SAX processing -- using the template above, it is simple to modify the program to meet whatever requirements you have. One use to which we've put XML is for reliable communication between ASP and JSP, and as we make information available over XML, we usually find it can be used elsewhere.

Download the sample files for this tutorial here.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links

Rate This Article

  • 1
    Poor
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
    Great

Post A Comment

You need to be a member of the SitePoint Forums to comment on this post. Sign Up

Already a member? Post using your SitePoint Forums account: