Published on ONJava.com (http://www.onjava.com/)
 See this if you're having trouble printing code examples

JSP and Servlets




In the world of server page acronyms, XSP is gaining recognition. It's the next evolution of server pages.

Sue Spielman will be speaking about XSP at the O'Reilly Conference on Enterprise Java, March 26-29, in Santa Clara, California.

XSP stands for eXtensible Server Pages and is one of the core technologies available in Cocoon. Cocoon is one of the seven current parts of the Apache XML project. The new Cocoon paradigm is based on the fact that document content, style, and logic are often created by different individuals or working groups. Cocoon aims for a complete separation of the three layers. In other words, Cocoon allows content, logic, and style to be separated into different XML files, and it uses XSL transformation capabilities to merge them.

While having similar concepts to Java Server Pages (JSP), there are a number of differences present in XSP. We will look at both technologies to see how they stack up against each other. This article assumes you have at least some understanding of XML and its terminology.

XSP Technology

The main concept behind a web site using XML is the separation of content, logic, and presentation. XSP provides the front-end portion of an XML framework. Providing dynamic XML pages that are parsed and transformed by the framework allows application interoperability, yet the pages are constructed and stored as static files on a file system.

Just as Java is aimed at providing a clear separation of content from application and business logic, XSP seeks to provide the same for XML-based applications. Although many of the currently available XML frameworks allow this separation of layers within compiled code, changes to the formatting of actual data in an XML document still require Java code and subsequent recompilation.

XML browsers are useless without some predefined semantics. This is one of the reasons why XSL (the eXtensible Stylesheet Language) was proposed and designed. XSL is divided into two parts: transformation (XSLT) and formatting objects (variously referred to as FO, XSL:FO, or simply XSL). Both are XML DTDs that define a particular XML syntax: every XSL or XSLT document is a well-formed XML document.

The Cocoon publishing model is heavily based on XSLT's transformation capabilities. XSLT allows complete separation of content and style, something everyone writing web applications has been striving toward but has been unsuccessful at. This separation is much harder to obtain with HTML, even if CSS2 or other styling technologies are being used. But Cocoon goes further and defines a way of separating content and style from the programming logic that drives server-side behavior. The XSP language defines an XML DTD for separating content and logic for compiled server pages.

In dynamic content generation technology, content and logic are combined. There is typically a mix of static content and dynamic logic that work together to create the final result, usually using run-time or time-dependent input. XSP is no exception. It defines syntax to mix static content and programmatic logic in a way that is independent of both the programming language used and the binary results that the final source rendering generate.

It should be understood that XSP is just a piece of the framework. In much the same way that formatting objects mix style and content, XSP objects mix logic and content. On the other hand, since both are XML DTDs, XSLT can be used to move from pure content to these final DTDs, placing the style and logic in the transformation layers and guaranteeing complete separation and easier maintenance.

JSP Technology

The intention of JSP technology was to provide a clean separation between content and presentation. While making great strides in doing so, it falls somewhat short. While JSP has simplified many of the server-side Java programming details, it still can't quite make the clean break it was intended to. If you have delivered a large-scale application using JSP you will no doubt agree.

JSP mingles content (pure data) with presentation in the same way static HTML does. JSP allows tags and inline Java code to be inserted into an otherwise normal HTML page. When the JSP page is requested, the resulting code is executed in a Servlet engine and the results are inserted right into the output HTML. JSPs tend to be specific for an application because they are designed from the outset for the delivery of output from that application. A typical JSP pages contains static HTML/XML components, JSP tags, and optional snippets of Java code called scriptlets. You can create and maintain JSP pages with your favorite HTML/XML tool.

By using XML-like tags, scripting elements, scriptlets, and directives, a content developer can accomplish quite a lot. Scripting elements and expressions allow for runtime evaluation of variables. Directives can be used to control certain aspects of the actual workhorse servlet's operation. To simplify the scripting elements, a JSP developer has access to a number of predefined variables such as request, response, in, and out. These variables represent, respectively, HttPServletRequest, HttpServeletReponse, PrintWriter, and BufferedReader. There are a few other predefined variables but for this discussion those listed should suffice. Scriptlets provide a mechanism to insert code into the servlet's service method. In addition, JSP can work hand-in-hand with JavaBeans. By embedding beans within a JSP, it is possible to encapsulate functionality for a JSP as well as reuse the bean in other development efforts. Special treatment is given to beans in a JSP, which can make for a cleaner, less cluttered JSP page. For example, parameter values in a client request can automatically be used to set a bean's properties. Beans also have scope and can be used per request, between pages, or even throughout an application.

Custom Tag libraries also provide a way for JSP to separate content from presentation. Using custom tag libraries it is possible to create business logic that is almost completely hidden from the presentation developer. The only thing that the presentation developer has to know is how to reference the tag library and use the tag. This could be as simple as one line of code, or it could be more complicated if tag interaction is required.

As you can see, JSP technology is very powerful and useful but is not ideal.

The Object Models

The XSP model works on the concept of processor and producers. A processor is a Cocoon Java type that takes a DOM tree as input and produces another (possibly modified) DOM tree as output. Think of it as a filter in a command pipeline. The XSP engine is implemented as a Cocoon processor that accepts an XSP page as input. The first time a given XSP page is processed, it is translated into an equivalent source program that is then compiled, loaded, and executed. Subsequent requests for the same XSP page result in the execution of the generated program. As you may expect, the output DOM tree returned by the XSP engine processor is actually built by the generated program.

XSP pages are compiled into Cocoon producers. A producer is a Cocoon Java type normally used to feed the initial XML content to the Cocoon processing pipeline. For example, when Cocoon serves a static, "regular" XML document, file contents are actually delivered by Cocoon's built-in FileProducer.

Where JSP technology generate servlets, XSP generates producers instead. This is because, among other reasons, the servlet model does not yet provide a mechanism for portably and efficiently post-processing XML content.

JSP and XSP share many of the same built-in objects. XSP defines an abstract producer (XSPPage) as the base class for generated programs. The request and response are available with a slight change to the wrapper provided in Cocoon. Access to ServeltOutputStreamObject and its associated writer are not provided. HttpSession and ServletContext are provided as well.

XSP has a few additions to its object model. XspNodeStack is a java.util.Stack used to control element nesting in the XSP page Document object; xspCurrentNode and xspParentNode are org.w3c.Node objects. xspParser is a Cocoon-supplied DOM parser, which may be used to create new documents and parse external XML documents. In addition to the objects already listed, the XSPPage contains a xspExpr() method than can be used to wrap any Java value as an org.w3c.Text object. There is also an XSPUtil Class automatically imported that offers a number of DOM, HTTP, and file manipulation services implemented as public static methods. These include cloneNode, toMarkup encodeMarkup, formEncode, formDecode, pathComponent, fileComponent, baseName, split, and isAlphaNumeric.

A Minimal XSP Page

An XSP page is an XML page with the following requirements.

Usually you will also require further processing of the resulting page -- perhaps with a stylesheet -- to transform the resulting code into a readable form for the viewer.

Cocoon processing instructions act upon a whole document, which generates a result document, which will in turn be passed to the next Cocoon processor, rather like a pipeline. This is similar to Servlet chaining.

What follows is a minimal XSP page that shows a simple page counter. (Note that the <-- lines are comments):

<-- required for every XML page-->
<?xml version="1.0"?>
<-- first process this page with the Cocoon XSP Processor -->
<?cocoon-process type="xsp"?>
<-- then run the results through the XSLT processor -->
<?cocoon-process type="xslt"?>
<-- Tell the XSLT processor which stylesheet to use -->
<?xml-stylesheet href="page-html.xsl" type="text/xsl"?>
<-- This is required for an XSP page -->
<xsp:page language="java" xmlns:xsp="http://www.apache.org/1999/XSP/Core">
<-- <xsp:logic> tags specify definitions of things in the language that is used on this XSP page -->
<-- usually functions and class-wide variables. -->
static private int counter = 0;

private synchronized int count() {
return counter++;

This is the bulk of the page content specified as general XML. The first element that you place here (in this case <page>) will become the document root element of the XML document that will be generated after the XSP processor has finished. The <xsp:expr>count()</xsp:expr> element here is saying "call count() and convert the result into a text node". <xsp:expr> is used wherever you need to insert live data into the output document.

<p>This page has been requested <xsp:expr>count()</xsp:expr> times.</p>

The output of the XSP processor will produce the following page the first time the page is requested.

<?xml version="1.0"?>
<?cocoon-process type="xslt"?>
<?xml-stylesheet href="page-html.xsl" type="text/xsl"?>
<p>I've been requested 0 times.</p>

A Minimal JSP Page

A minimal JSP page is nothing more than an HTML page. Although not very interesting in terms of any dynamic content, it can be compiled in the Servlet engine.

Different Types of Pages

There are typically three types of pages that can be developed with either JSP or XSP technology.

The first and, admittedly, the worst uses embedded logic. In this case, code is placed directly into the XML or JSP. This defeats the purpose of separation of tasks. It also makes the page prone to updates and changes. For any production quality project, this is definitely not the development option you want to employ, unless you want to be looking for a new job soon.

The second, preferable way matches parts of the original document, either by a stylesheet in the XSP case or template in the JSP case, and replaces those parts with sections of logic code. In the XSP scenario, an XSP page is generated from the original XML page, rather than the original XML page being an XSP page. The result of this transformation is a canonical XSP page. This will then be "executed" and the result will be an XML page with all the variable pieces replaced with actual values. Once again, the XSL stylesheet transforms the final outcome into a HTML page.

The third case could be dealing with either of the two previous scenarios, the only difference being where the tab library exists. The taglibs are central libraries that can be referred to anywhere within an XSP page. The most important aspect of the taglib is that it has an XML URI namespace declaration which is declared in the original logic sheet and matched in the <xsp:page> xmlns attribute in the XSP case. The Cocoon properties file also needs to know where to find the XSL file.

For a JSP, the tab library is defined in the directive

<%@ taglib uri="/myTldExample.tld" prefix="example" %>

A sample XSP page might look like

<xsp:page xmlns:example="http://www.oreilly.com/xspExample">

The logic sheet file might look like

<xsl:stylesheet version="1.0"

And finally the cocoon.properties would have the following entry:

processor.xsp.logicsheet.example.java = file:///oreilly/xspExample.xsl

A Few Small Differences

If you are developing in either technology there are probably a few small differences that you will notice.

Core tags

Each of the technologies has a set of core tags that are used throughout.

The XSP tag set consists of the following core tags.


Root of all XSP pages and specifies the scripting language and the tag libraries used by a particular XSP page


Top-level element encloses source program-level declarations such as <xsp:include>. This element is used to import external module definitions in a language-dependent way


Embeds procedural logic in an XSP page. Enclosed code is transcribed verbatim into the generated XSPPage producer. Other XSP or user markup may be nested inside this tag.


Embeds "regular" XML content inside an <xsp:logic> block so that no nested additional <xsp:logic> sections are required


Inlines a program expression as a Text node, except when used directly inside another <xsp:> element, where it is substituted as an expression, not a node. If you want to substitute an <xsp:expr> tag as a node inside another XSP tag, you must enclose it in an <xsp:content> element.


Dynamically builds an element when its attribute values are not known at compile time.


Dynamically provides attribute values for a given element (which can be specified statically as markup or dynamically by means of <xsp:element>). It's typically used in conjunction with <xsp:expr>, where the substituted expression is always cast to String


Dynamically creates a processing instruction


Dynamically creates an XML comment

The JSP Reference syntax can be found on Sun's Java site.

Which Technology is Right for Me?

So which technology is best for your project? The answer: it depends. There are pros and cons to both as we've seen, but each should be weighed according to your project needs.

If you are looking for a solution that maximizes reusable code across applications, then XSP is probably your answer. XSP allows the separation of content from presentation. This separation allows developers to handle content generation. The XSP page can be generated from a servlet or other Java code as well as being static. XML and XSL authors can handle presentation and styling through modification of the XSL stylesheet applied to the XSP page. Just as easily, XSP solves the other significant deficiency of JSP. Because XSP processing occurs before any stylesheets are applied, the resultant XML document can be transformed into any other format. This maintains all the advantages of XML. The XSP page can be transferred between applications as well as being used just for presentation.

If you want to keep your development teams clearly defined, then, again, XSP is probably your answer. The introduction of the JSP environment made significant improvements in dynamic web application development by better separating the application developer from the presentation designers. However it still involves a fair amount of interaction between the two. There is frequently a need for inline Java code to determine the correct presentation necessary when dealing with dynamic content. Custom tag libraries have helped address this and require the presentation person to be less knowledgeable about what the logic is actually doing. But that person still needs to understand how to use the tag library, which is usually more then a presentation person wants or needs to know.

XSP and accompanying framework focuses XSL and XSLT stylesheets for the presentation layer written by presentation designers, XML for the content provided by the content authors, and application logic layer and tagset generated by the application developer. The interaction of the technologies in the Cocoon framework is what glues everything together and allows XSL plus XML plus embedded tags to generate an HTML document. The tasks themselves are clearly separated.

If your main concern is getting a product out the door with the least risk factor, then JSP is your answer. JSPs are popular and widely understood, while XSP and Cocoon are still emerging. This is not something to overlook. For large scale projects, it is always necessary to evaluate how much effort it would take to bring a new developer up to speed and the pool of talent you can draw from. In addition, existing HTML and XML tools can be used for JSP development, making the overall time it takes to get rolling relatively short.

Sue Spielman is an associate editor for ONJava.com, covering JSP and Servlets technologies. She is also President and Senior Consulting Engineer for Switchback Software LLC.

Return to ONJava.com.

Copyright © 2009 O'Reilly Media, Inc.