Lucky Dip Logo
Powered by PlusNet. PlusNet broadband.
Patrick's Lucky Dip
Home > Java > JSP Tutorial > A Simple Web Service

Patrick Haston
9 February 2009

JSP Tutorial - Building a Simple Web Service

There are several flavours of web service, but the easiest to build and use are REST-based web services. Wikipedia defines these as Representational State Transfer and explains that strictly speaking they are not true web services. The principles are the same as SOAP-based web services, just with less clutter.

The very simplest web service just returns a static xml document and is spectacularly useless, but we can add functionality and complexity later.

Lets create a new Project in our LearningJSP workspace called WebServiceProvider. Change the properties of the Project and set the J2EE Web Application Name and J2EE Web Application Root to webserviceprovider.

Within the project create a new jsp page called example1.jsp. Switch to the source code view and delete everything - we're not going to return an html page, the content is going to be an xml file. Type in the following:

<?xml version="1.0" encoding="UTF-8"?>

<example>
  <message>Hello World</message>
</example>

If you're new to XML you'll not recognise the syntax but you should be able to guess at the meaning. That's one of the great strengths of XML as a file format - it's human readable. The first line just defines the file as XML. XML allows you to define your own tags, so that what I've done. I've wrapped the famous Hello World message in <message> tags, and wrapped the whole lot in the <example> tags.

Run this and you should see the whole lot displayed: your browser doesn't understand the xml tags we've made up so it just displays the page with all the tags rather than just the message. Make a note of the url displayed in the browswer, we're going to need that soon.

Now create a second Project called WebServiceClient. Set both the J2EE Web Application Name and J2EE Web Application Root to webserviceclient.

Create a new Java Class called CallWebService and type in the following:

package uk.co.patrickhaston.webserviceclient;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class CallWebService 
{
  private String _endpoint =
		"http://localhost:8081/webserviceprovider/example1.jsp";
  // This needs to be set to the url of your new jsp page.
  
  public CallWebService()
  {
  }
  
  public String getMessage()
  {
    String xml = "";
    try
    {
      // Create a new URL object
      URL url = new URL( _endpoint );
      // the URL is created with the string called _endpoint.
      
      // Get an input stream for reading
      InputStream in = url.openStream();

      // Create a buffered input stream for efficency
      BufferedInputStream bufIn = new BufferedInputStream(in);

      // Repeat until end of file
      for (;;) // a for loop which never ends
      {
        int data = bufIn.read();

        // Check for EOF
        if (data == -1)
            break; // exit from the for loop
        else
            xml = xml + ( (char) data); // add the data to the string
      }

    }
    catch (MalformedURLException mue)
    {
      xml = "Invalid URL";
    }
    catch (IOException ioe)
    {
      xml = "I/O Error - " + ioe.getMessage();
    }
    catch( Exception e )
    {
      xml = "Unexpected Error in CallWebService.getMessage(): " + 
				e.getMessage();
    }
    return xml;
  }
}  

Compile this to make sure you've not got any typos.

Create a new jsp page called example1.jsp. Here's the code:

<%@ page contentType="text/html;charset=windows-1252"%>

<jsp:useBean
	id="callWebService"
	scope="request"
	class="uk.co.patrickhaston.webserviceclient.CallWebService"
/>


<%
String xml = "";


// get the action
try
{
  xml = callWebService.getMessage(message);
}
catch (Exception e)
{
  message = "Error: " + e.getMessage();
}

%>


<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <title>Web Service Example 1</title>
  </head>
  <body>
    <h1>Web Service Example 1</h1>
    xml: <%=xml%>
  </body>
</html>

It's a very simple jsp page: there's the bean declaration at the beginning, then a bit of Java code where we declare a String called xml and populate by calling our java class. Then the bit of html is where we display the result.

Run it and see what happens: you should get the message Hello World displayed after the prompt xml. What happened to the xml tags? Look at the source code for your page and you will see that they are still there, it's just that because the page your are viewing is an html page, the browser simply ignores any tags it doesn't understand. It is not a good idea to rely on this functionality in real-life, but it keeps the example simple.

The next example shows how to create and use an interactive web service, which is much more useful.