BEA Logo BEA WebLogic Server Release 6.1

  Corporate Info  |  News  |  Solutions  |  Products  |  Partners  |  Services  |  Events  |  Download  |  How To Buy

   Programming WebLogic XML:   Previous topic   |   Next topic   |   Contents   |  Index

 

Developing XML Applications with WebLogic Server

 

The following sections describe how to use the Java programming language and WebLogic Server to develop XML applications. It is assumed that you know how to use Java Servlets and Java Server Pages (JSPs) to write Java applications. For information about how to write servlet and JSP applications, see Programming WebLogic HTTP Servlets and Programming WebLogic JSP .

Using WebLogic Server Features For XML Application Development

To facilitate XML application development and the work required to move XML applications built on WebLogic Server to other Web application servers, WebLogic Server implements the Java API for XML Parsing (JAXP). JAXP was developed by Sun Microsystems to make XML applications portable; it provides basic support for parsing and manipulating XML documents through a standardized set of Java platform APIs. JAXP 1.0.1, included in the WebLogic Server distribution, is configured to use the built-in parser. Therefore, by default, XML applications built using WebLogic Server use JAXP.

The WebLogic Server distribution contains the interfaces and classes needed for JAXP 1.0.1. JAXP 1.0.1 contains explicit support for SAX 1.0 and DOM Level 1. The Javadoc for JAXP is included with the WebLogic Server online reference documentation. The WebLogic Server distribution does not include the Sun Projectx parser.

Advantage of Using JAXP

When you write XML applications, the application must get the XML document and parse it to make its contents available to the application. To accomplish this task, you can use either the SAX or the DOM API. Both APIs provide extensive functionality and are very useful. However, to use either API, you must import and reference a parser class from a parser vendor's Java code. The problem with this approach is twofold:

These problems could be avoided if the XML parser were completely pluggable. The Java API for XML Parsing (JAXP) provides a parser Pluggability Layer. The JAXP Pluggability Layer allows a compliant SAX or DOM parser to be accessed through factory classes in the javax.xml.parsers package.

Using JAXP with SAX

The following code example shows how to provide an implementation of the org.xml.sax.HandlerBase class to a SAXParser implementation and then parse an XML document:

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

...
MyHandler handler = new MyHandler();
// MyHandler extends org.xml.sax.HandlerBase.

  //Obtain an instance of SAXParserFactory.
SAXParserFactory spf = SAXParserFactory.newInstance();
//Specify a validating parser.
spf.setValidating(true); // Requires loading the DTD.
//Obtain an instance of a SAX parser from the factory.
SAXParser sp = spf.newSAXParser();
//Parse the documnt.
sp.parse(inputFile, handler);
...

Note: If you want to use a parser other than the default, built-in parser, you must use the WebLogic Server Administration Console to specify the parser in the XML Registry; otherwise the newInstance method returns the built-in parser. For instructions about configuring WebLogic Server to use a parser other than the built-in parser, see XML Registry Configuration Tasks.

Using JAXP and DOM

The following code example shows how to provide an implementation of the org.w3c.dom.Document class to a DocumentBuilder implementation and then parse an XML document:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

...
//Obtain an instance of DocumentBuilderFactory.
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
//Specify a validating parser.
dbf.setValidating(true); // Requires loading the DTD.
//Obtain an instance of a DocumentBuilder from the factory.
DocumentBuilder db = dbf.newDocumentBuilder();
//Parse the document.
Document doc = db.parse(inputFile);
...

Note: If you want to use a parser other than the built-in parser, you must use the WebLogic Server Administration Console to specify the parser in the XML Registry; otherwise the newInstance method returns the built-in parser. For instructions about configuring WebLogic Server to use a parser other than the built-in parser, see XML Registry Configuration Tasks.

XML Registry Configuration Options

As mentioned previously, you use the Administration Console XML Registry to configure the following:

When you make configuration changes using the XML Registry, the changes take effect immediately, that is, it is not necessary to recompile the XML application code or to restart the server. You can make changes at deploy time or run time without modifying and recompiling the XML application code or restarting the server.

Servlet Programming Features

Support for the setAttribute and getAttribute methods was added to version 2.2 of the Java Servlet Specification. Attributes are objects associated with a request. The request object encapsulates all information from the client request. In the HTTP protocol, this information is transmitted from the client to the server by the HTTP headers and message body of the request.

With WebLogic Server, you can use these methods to parse XML documents. The setAttribute method is used for SAX mode parsing; the getAttribute method, for DOM mode parsing.

Using the org.xml.sax.HandlerBase Attribute to Parse a Document

The following code example shows how to use the setAttribute method:

import weblogic.servlet.XMLProcessingException;
...
public final void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
try {// MyHandler extends org.xml.sax.HandlerBase.
request.setAttribute(
"org.xml.sax.HandlerBase", new MyHandler());
} catch(XMLProcessingException xpe) {
System.out.println("Error in processing XML");
xpe.printStackTrace();
return;
}
...

Note: This code example shows a simple way to parse a document using SAX and the setAttribute method. This is a WebLogic Server convenience feature, and it is not supported by other servlet vendors. Therefore, if you plan to run your application on other servlet platforms, do not use this feature.

Using the org.w3c.dom.Document Attribute to Parse a Document

The following code example shows how to use the getAttribute method.

import org.w3c.dom.Document;
import weblogic.servlet.XMLProcessingException;

...

public final void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

try {
Document doc = request.getAttribute("org.w3c.dom.Document");
} catch(XMLProcessingException xpe) {
System.out.println("Error in processing XML");
xpe.printStackTrace();
return;
}
...

Note: This code example shows a simple way to parse a document using DOM and the getAttribute method. This is a WebLogic Server convenience feature, and it is not supported by other servlet vendors. Therefore, if you plan to run your application on other servlet platforms, do not use this feature.

Generating XML

This section describes how to generate XML documents from a DOM document tree and by using JSP.

Generating XML from a DOM Document Tree

To generate an XML document from a DOM document tree, you can use the class weblogic.apache.xml.serialize. You can use this class to convert a DOM document tree to XML text. For a description of this class, see Javadoc for weblogic.apache.xml.serialize.

The following code example shows how to used this class.

package test;

import java.io.OutputStreamWriter;
import java.util.Date;
import java.text.DateFormat;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import weblogic.apache.xerces.dom.DocumentImpl;
import weblogic.apache.xml.serialize.DOMSerializer;
import weblogic.apache.xml.serialize.XMLSerializer;

public class WriteXML {

  public static void main(String[] args) throws Exception {

    // Create a DOM tree.
Document doc= new DocumentImpl();
Element message = doc.createElement("message");
doc.appendChild(message);
Element text = doc.createElement("text");
text.appendChild(doc.createTextNode("Hello world."));
message.appendChild(text);
Element timestamp = doc.createElement("timestamp");
timestamp.appendChild(
doc.createTextNode(
DateFormat.getDateInstance().format(new Date()))
);
message.appendChild(timestamp);

    // Serialize the DOM to XML text and output to stdout.
DOMSerializer xmlSer =
new XMLSerializer(new OutputStreamWriter(System.out),null);
xmlSer.serialize(doc);
}
}

Generating XML Documents by Using JSP

The most common reason for using JSP is to generate HTML, but JSP can also be used to generate an XML document.

The main requirement for using JSP to generate XML is that the JSP page set the content type of the page as follows:

<%@ page contentType="text/xml"%>
... XML document

The following code shows an example of how to use JSP to generate an XML document:

<?xml version="1.0">

<%@ page contentType="text/xml" import="java.text.DateFormat,java.util.Date" %>

<message>
<text>
Hello World.
</text>
<timestamp>
<%
out.print(DateFormat.getDateInstance().format(new Date()));
%>
</timestamp>
</message>

For more information about using JSP to generate XML, see http://java.sun.com/products/jsp/html/JSPXML.html.

Transforming XML Documents

WebLogic Server includes a built-in XSLT processor, which is based on the Apache Xalan XSLT processor. The built-in XSLT processor uses the built-in parser by default. JAXP does not provide a standard API to access the built-in XSLT processor, so the XSLT processor must be handled in your application programmatically.

In an XSLT transformation, an XSLT processor reads both an XML document and an XSLT style sheet. Based on the instructions in the XSLT style sheet, the transformer outputs a new XML document, an HTML document, a WML document, and so on.

WebLogic Server supports two ways of using the XSLT processor:

Using the XLST Processor to Transform XML Documents

The following code example shows how to construct a simple DOM tree (for the same XML document used in HelloWorld.jsp) and then serialize it to XML text. In the example, the XML text is printed to the standard output using the System.out method.

Note: The following code example was taken from the Apache Xalan samples, which are available at http://xml.apache.org.

 *
* This code example was taken from code examples provided by the
* Apache Software Foundation. It consists of voluntary
* contributions made by many individuals on behalf of the Apache
* Software Foundation and was originally based on software
* copyright (c) 1999, Lotus Development Corporation.,
* http://www.lotus.com. For more information on the Apache
* Software Foundation, please see <http://www.apache.org/>.
*/

import org.xml.sax.SAXException;
import org.apache.xalan.xslt.XSLTProcessorFactory;
import org.apache.xalan.xslt.XSLTInputSource;
import org.apache.xalan.xslt.XSLTResultTarget;
import org.apache.xalan.xslt.XSLTProcessor;

/**
* Simple sample code to show how to run the XSL processor
* from the API.
*/
public class SimpleTransform
{
public static void main(String[] args)
throws java.io.IOException,
java.net.MalformedURLException,
org.xml.sax.SAXException
{
// Have the XSLTProcessorFactory obtain a interface to a
// new XSLTProcessor object.
XSLTProcessor processor = XSLTProcessorFactory.getProcessor();

    // Have the XSLTProcessor processor object transform "foo.xml"
// to System.out, using the XSLT instructions found in "foo.xsl".

    processor.process(new XSLTInputSource("foo.xml"),
new XSLTInputSource("foo.xsl"),
new XSLTResultTarget(System.out));
}
}

For additional information about the Xalan samples, see the Apache Xalan Javadoc and the Overview and Getting Started documents on the Apache Web site at http://xml.apache.org/xalan.

Using the JSP Tag to Transform XML Documents

WebLogic Server provides a small JSP tag library for convenient access to an XSLT processor from within a JSP. You can use this tag to transform XML documents, but it is not required.

The JSP tag library consists of one main tag, x:xslt, and two subtags you can use within the x:xslt tag: x:stylesheet and x:xml.

XSLT JSP Tag Syntax

The XSLT JSP tag syntax is based on XML. A JSP tag consists of a start tag, an optional body, and a matching end tag. The start tag includes the element name and optional attributes.

The following syntax describes how to use the three XSLT JSP tags provided by WebLogic Server in a JSP. The attributes are optional, as are the subtags x:stylesheet and x:xml. The tables following the syntax describe the attributes of the x:xslt and x:stylesheet tags; the x:xml tag does not have any attributes.

<x:xslt  [xml="uri of XML file"]
[media="media type to determine stylesheet"]
[stylesheet="uri of stylesheet"]
<x:xml>In-line XML goes here
</x:xml>
<x:stylesheet [media="media type to determine stylesheet"]
[uri="uri of stylesheet"]
</x:stylesheet>
</x:xslt>

The following table describes the attributes of the x:xslt tag.

x:xslt Tag Attribute

Required

Data type

Description

xml

No

String

Specifies the location of the XML file that you want to transform. The location is relative to the document root of the Web application in which the tag is used.

media

No

String

Defines the document output type, such as HTML or WML, that determines which stylesheet to use when transforming the XML document.

This attribute can be used in conjunction with the media attribute of any enclosed x:stylesheet tags within the body of the x:xslt tag. The value of the media attribute of the x:xslt tag is compared to the value of the media attribute of any enclosed x:stylesheet tags. If the values are equal, then the stylesheet specified by the uri attribute of the x:stylesheet tag is applied to the XML document.

NOTE: It is an error to set both the media and stylesheet attributes within the same x:xslt tag.

stylesheet

No

String

Specifies the location of the stylesheet to use to transform the XML document. The location is relative to the document root of the Web application in which the tag is used.

NOTE: It is an error to set both the media and stylesheet attributes within the same x:xslt tag.

The following table describes the attributes of the x:stylesheet tag.

x:stylesheet Tag Attribute

Required

Data type

Description

media

No

String

Defines the document output type, such as HTML or WML, that determines which stylesheet to use when transforming the XML document.

Use this attribute in conjunction with the media attribute of enveloping x:xslt tag. The value of the media attribute of the x:xslt tag is compared to the value of the media attribute of the enclosed x:stylesheet tags. If the values are equal, then the stylesheet specified by the uri attribute of the x:stylesheet tag is applied to the XML document.

uri

No

String

Specifies the location of the stylesheet to use when the value of the media attribute matches the value of the media attribute of the enveloping x:xslt tag. The location is relative to the document root of the Web application in which the tag is used.

XSLT JSP Tag Usage

The x:xslt tag can be used with or without a body, and its attributes are optional. This section describes the rules that dictate how the tag behaves depending on whether you specify a body or one or more attributes.

If the x:xslt JSP tag is an empty tag (no body), the following statements apply:

Caution: It is an error to set both the media and stylesheet attributes.

An XSLT JSP tag that has a body may contain <x:xml> tags and/or <x:stylesheet> tags.

Transforming XML Documents Using an XSLT JSP Tag

To use an XSLT JSP tag to transform XML documents, perform the following steps:

  1. Open the xmlx.zip file in the BEA Home/wlserver6.0/ext directory, extract the xmlx-tags.jar file, and put it in the /lib directory of your Web application, where BEA Home is the top-level directory in which you installed the WebLogic Server distribution.

  2. Add a <taglib> entry to the web.xml file. For example:

    <taglib>
    <taglib-uri>xmlx.tld</taglib-uri>
    <taglib-location>/WEB-INF/lib/xmlx-tags.jar</taglib-location>
    </taglib>

  3. To use the tags, add the following line to your JSP page:

    <%@ taglib uri="xmlx.tld" prefix="x"%>

  4. Configure the processor. The following procedure shows a generic way to configure the processor:

    1. Enter the following code line to create an xslt.jsp file:

      <%@ taglib uri="xmlx.tld" prefix="x"%><x:xslt/>

    2. Register the xslt.jsp file in your web.xml file, as follows:

      <servlet>
      <servlet-name>myxsltinterceptor</servlet-name>
      <jsp-file>xslt.jsp</jsp-file>
      </servlet>
      <servlet-mapping>
      <servlet-name>myxsltinterceptor</servlet-name>
      <url-pattern>/xslt/*</url-pattern>
      </servlet-mapping>

    3. Put your XML/DTD/XSL documents or servlets in your Web application.

    4. Add an xslt prefix to the pathname for the XML document (for example, change docs/fred.xml to xslt/docs/fred.xml) and then access the document. Because of the <url-pattern> entry in the web.xml file, WebLogic Server automatically runs the XSLT processor on the XML document and sets the default stylesheet in the document.

    5. To define media type, add code to the JSP to determine the media type for the XML document and the content type for the output.

    6. Pass the media type into the xslt tag and then set the content type of the response object.

Note: The other forms of the XSLT JSP tag are used when stylesheets are not specified in the XML document or your XML stylesheet can be generated inline.

Example of Using the XSLT JSP Tag in a JSP

The following snippet of code from a JSP shows how to use the XSLT JSP tag to transform XML into HTML or WML, depending on the type of client that is requesting the JSP. If the client is a browser, the JSP returns HTML; if the client is a wireless device, the JSP returns WML.

First the JSP uses the getHeader() method of the HttpServletRequest object to determine the type of client that is requesting the JSP and sets the myMedia variable to wml or html appropriately. Using the x:xslt and x:stylesheet in unison, if the JSP set the myMedia variable to html, then it applies the html.xsl stylesheet to the XML document contained in the content variable. Similarly, if the JSP set the myMedia variable to wml, then it applies the wml.xsl stylesheet.

<%
String clientType = request.getHeader("User-Agent");
// default to WML client
String myMedia = "wml";

// if client is an HTML browser

   if (clientType.indexOf("Mozilla") != -1) {
myMedia = "http"
}
%>

<x:xslt media="<%=myMedia%>">
<x:xml><%=content%></x:xml>
<x:stylesheet media="html" uri="html.xsl"/>
<x:stylesheet media="wml" uri="wml.xsl"/>
</x:xslt>

Using Parsers Other Than the Built-In Parser

This section explains how to use parsers other than the built-in parser. Specifically, it discusses these topics:

Using the WebLogic Parser Generator to Generate Custom Parsers

In a highly scalable Internet application, parser performance can be a bottleneck. To address this problem, WebLogic Server provides the WebLogic Parser Generator. Using the WebLogic Parser Generator you can create a parser that is tailored to a particular DTD. This parser will be much more efficient and faster than a general-purpose parser that can handle any document type. Generated parsers use the SAX API and should be used to parse only XML documents that are based on the DTD used to generate the parser.

Limitations of Generated Parsers

The following limitations apply to generated parsers:

Performance and Usage Considerations for Generated Parsers

When deciding whether to use a generated parser, keep in mind the following considerations:

Generating a Custom Parser

To generate a customized parser, perform the following steps:

  1. Make sure the xmlx.jar file is in BEA Home\wlserver6.0\lib, where BEA Home is the top-level directory in which you installed the WebLogic Server distribution.

  2. Run the parser generator against the DTD for which you want to generate a custom parser. The following is a typical execution command using the wml12.dtd on a Microsoft Windows platform:

    java weblogicx.xml.parserc -d %SERVER_CLASSES% -root wml
    -package weblogicx.xml.parsers wml12.dtd

    Where:

  3. If you want to examine the generated parser's code, use the -keepgenerated option.

  4. Use the Administration Console to register wmlparser in the XML Registry. For instructions about registering a parser in the XML Registry, see Configuring a Custom-Generated Parser.

Once this procedure is completed, as long as you use JAXP to parse a WML document, WebLogic Server will use wmlparser to do SAX parsing.

Using Parsers Other Than the Built-In Parser

If you use JAXP to parse your XML documents, the WebLogic Server XML Registry (which is configured through the Administration Console) offers the following options:

If you elect to use the API of a general-purpose parser instead of JAXP, you must control all parsing options through the parser's API; the WebLogic Server XML Registry does not control parsing options when the API of a general-purpose parser is used. For example, if you elect to use the built-in parser's proprietary API, rather than JAXP, to parse documents, then you must also use the built-in parser's proprietary API to control all parsing options.

For instructions on how to use the XML Registry to configure parsing options, see XML Registry Configuration Tasks.

Setting Up Local Entity Resolution Using the XML Registry

For instructions about setting up local entity resolution, see Configuring Local Entity Resolution.

 

Back to Top