[ Team LiB ] Previous Section Next Section

A "Hello World" XML Page

In a minimal XML page you need two things: a heading identifying the page as an XML page, and a single pair of tags that represents the root of the data. Think of the root tags as being like the <HTML> </HTML> tags in an HTML document. They enclose everything else. An XML document must have only one pair of root tags. Everything else in the document must be within those two tags. An XML tag defines an XML "element." The root tags define the "root element" or "document element" of an XML document.

Listing 19.1 shows a "Hello World" XML page.

Listing 19.1 Source Code for HelloWorld.xml
<?xml version=_1.0_?>
    Hello World

The <?xml version="1.0"?> tag must be present in any XML file. The <greeting> </greeting> tag pair is the root of the document.

Sending XML from a JSP

You can create XML JSPs the same way you create HTML pages. The only difference is that you must set the content type of your page to text/xml. To set the content type, use the <%@page%> tag, like this:

<%@ page contentType="text/xml" %>

Listing 19.2 shows the "Hello World" XML page as a JSP.

Listing 19.2 Source Code for XMLHelloWorld.jsp
<%@ page contentType="text/xml" %>

<?xml version="1.0"?>
    Hello World!

Figure 19.1 shows the XMLHelloWorld JSP from Internet Explorer 6. As you can see, Internet Explorer shows you the XML source code.

Figure 19.1. Internet Explorer shows you XML source code.


Sending XML from a Servlet

Sending XML from a servlet is just as easy as sending HTML. The only difference is that you must set the content type to text/xml as you did with the JSP. Because you always need to set the content type in a servlet (unless you don't send a response at all), sending XML is just as easy as sending HTML.

Listing 19.3 shows a servlet that generates the "Hello World" XML page.

Listing 19.3 Source Code for XMLHelloWorldServlet.java
package examples;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class XMLHelloWorldServlet extends HttpServlet
    public void service(HttpServletRequest request,
        HttpServletResponse response)
        throws ServletException, IOException

        PrintWriter out = response.getWriter();

        out.println("<?xml version=\_1.0\_?>");
        out.println("    Hello World");

To run XMLHelloWorldServlet, you must create a WAR file containing the servlet and a WEB-INF/web.xml file as you have for other servlets. The WEB-INF/web.xml file should look like the code in Listing 19.4.

Listing 19.4 Source Code for web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmls="http://javqa.sun.com/xml/ns/j2ee"


If you deploy XMLHelloWorldServlet on your local machine in a WAR file named xml.war, the URL should be http://localhost/xml/xmlhello.

    [ Team LiB ] Previous Section Next Section