O'Reilly logo

Java SOA Cookbook by Eben Hewitt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Creating a POX over HTTP Service with Servlets

Problem

You want to get started writing RESTful web services without getting bogged down by an external framework. All you want is a class available at a URI that returns some XML.

Solution

Create a class that extends javax.servlet.http.HttpServlet; make sure that you set the response content type to text/xml. Use a transformer to write the XML out to your response.

Discussion

This is the simplest way to create an XML service without using any frameworks. For large-scale solutions, you probably want to at least consider using one of the available frameworks mentioned previously, but this approach represents the simplest thing that works.

In this example, you will define a servlet that returns XML to the requester. There is no schema associated with the XML, and no interface definition such as a WSDL. In a real-world service, this servlet would act as a frontend to some sort of enterprise information system. Here I just mock that out with a ProductCatalog class that contains a list of Product instances. The service itself consists of a servlet that invokes this “backend system” and transforms the result to XML for the output stream of the response.

First let’s look at the Product class because it uses no other class (Example 8-1).

Example 8-1. Product.java

package com.soacookbook;

import javax.xml.bind.annotation.XmlType;

@XmlType public class Product { private String id; private String name; private double price; public Product() { } //Getters ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required