http://www.developer.com/

Back to article

Creating Web Services from J2EE Components


September 20, 2004

Introduction

Web services are software processes that can be accessed and used from the Internet. Often, a software is exposed to the Web as a Web service because it needs to be available, reused, and shared by users from across the world. Web services represent a new architectural paradigm for software applications. Web services expose capabilities that are available to universal user applications and other Web services alike, via industry standard interfaces and protocols. The capabilities offerred by a Web service can fall into a variety of categories, including:

  1. To execute functions, such as calculating the interest on the balance of a credit card
  2. To retrieve data, such as fetching the balance of the credit card

Think of a business process as a conglomeration of several such capabilities. It can be inappropriate to integrate some of these capabilities within third-party applications. When these capabilities are exposed as Web services, they can be loosely coupled and dynamically discovered, thereby achieving the benefits of integration. Instead of tying all capabilities within a single application, Web services make their capabilities publicly available over the Net where a client application can simply invoke them by the URL address and compose an integration. Because the client application is free to implement the capabilities, it can do so in any language and platform that are compatible. This leads to a dramatic cut in the cost of development, maintanence, and time-to-market.



Click here for a larger image.

Figure 1: A Distributed Application Using Web Services-Based Capabilities

Aim of the Article

Creating Web services from various J2EE components and exposing them to the Net remain one of the critical aspects of a J2EE-compliant e-business. The flexibility and the versatility of the business process depend on this. In this article, we would like to address this issue from a programmer's point of view. We shall concentrate our efforts on a similar architecture with BEA Weblogic as the application server. We shall take some of the basic building blocks of a J2EE-based system, convert each to an individual Web service, and deploy on Weblogic.

In the following sections, we shall discuss the creation of a Web service for EJB, Servlet, JSP, HTML, and Java class. We shall illustrate each by creating a "Hello World" Web service from each of these components.

Creating a Web service from EJB

Enterprise Java Beans (EJB) is a component architecture for the development and deployment of enterprise level applications. Following are the Java classes that are needed to create a Hello World Web service from an EJB.

package examples ;
public class HelloBean implements javax.ejb.SessionBean
{
... ...
   public String hello()
   {
      System.out.println("hello()");
      return "Hello, World";
   }
}

HelloBean.java

package examples;
public interface HelloHome extends javax.ejb.EJBHome
{
   Hello create() throws java.rmi.RemoteException,
                         javax.ejb.CreateException;
}

HelloHome.java

package examples;
public interface Hello extends javax.ejb.EJBObject
{
   public String hello() throws java.rmi.RemoteException;
}

Hello.java

Copy all these files to a directory called examples. Include them in CLASSPATH and compile. The deployment descriptors that are necessary for deploying EJB Hello, ejb-jar.xml and Weblogic-ejb-jar.xml, are given below. These files should be available under the META-INF directory under examples.

<?xml version="1.0"?>
<!DOCTYPE ejb-jar PUBLIC
'-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN'
'http://java.sun.com/dtd/ejb-jar_2_0.dtd'>

<ejb-jar>
   <enterprise-beans>
      <session>
         <ejb-name>Hello</ejb-name>
         <home>examples.HelloHome</home>
         <remote>examples.Hello</remote>
         <ejb-class>examples.HelloBean</ejb-class>
         <session-type>Stateless</session-type>
         <transaction-type>Container</transaction-type>
     </session>
   </enterprise-beans>
</ejb-jar>

ejb-jar.xml

<?xml version="1.0"?>
<!DOCTYPE Weblogic-ejb-jar PUBLIC 
'-//BEA Systems, Inc.//DTD Weblogic 8.1.0 EJB//EN'
'http://www.bea.com/servers/wls810/dtd/Weblogic-ejb-jar.dtd'>
<Weblogic-ejb-jar>
   <Weblogic-enterprise-bean>
      <ejb-name>Hello</ejb-name>
      <jndi-name>ejb20-Hello-HelloHome</jndi-name>
   </Weblogic-enterprise-bean>
</Weblogic-ejb-jar>

Weblogic-ejb-jar.xml

Once the class files and deployment descriptors are ready, a JAR file is to be created using the following command from examples.

>jar -cf HelloWorld.jar *

This command will create a HelloWorld.jar file that contains the following structure:

META-INF/MANIFEST.MF
META-INF/ejb-jar.xml
META-INF/Weblogic-ejb-jar.xml
examples/Hello.class
examples/HelloHome.class
examples/HelloBean.class

MANIFEST.MF will be generated automatically while running the jar command. The HelloWorld.jar file is now ready for deployment.

Start the Weblogic Server. In the administration console, on the left hand side panel, just select the EJB Modules under Deployments. Select Deploy a new EJB Module option on the right hand side. In the directory tree structure displayed, select the directory in which HelloWorld.jar exists. Click the target module button. A screen will be displayed, stating "Review your choices and deploy." The EJB module name that is editable will be displayed. Click Deploy. Wait till the deployment ends and a success message is displayed.

To test the EJB Module that is deployed, just click the Testing tab. If the test is successful, a message will be displayed: "The EJB Hello has been tested successfully with a JNDI name of ejb20-Hello-HelloHome."

Creating a Web Service from a Servlet

A servlet is a Java program that extends the functionality of a Web server, generating dynamic content and interacting with Web applications using a request-response paradigm. Creating a Web service from a servlet involves deploying the servlet in Weblogic. The example of a HelloWorld servlet is given below.

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServlet;
import java.io.IOException;
import java.io.*;

public class HelloWorldServlet extends HttpServlet
{
   public void doGet(HttpServletRequest request,
                     HttpServletResponse response)
                    throws IOException, ServletException
   {
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      out.println("HelloWorld");
      out.close();
   }
   public void doPost(HttpServletRequest request,
                      HttpServletResponse response)
                     throws IOException, ServletException
   {
      doGet(request,response);
   }
}

HelloWorldServlet.java

Copy the HelloWorldServlet.java into HelloWorldServlet directory. Compile the Java file into the HelloWorldServlet/Web-inf/classes directory. Make sure that Servlet.jar is there in the CLASSPATH before compiling. The deployment descriptor needed for Servlet deployment is web.xml. It is given below.

<!DOCTYPE web-app
          PUBLIC "-//Sun Microsystems, Inc.
                   //DTD Web Application 2.3//EN"
                   "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
   <display-name>HelloWorldServlet</display-name>
   <servlet>
      <servlet-name> HelloWorldServlet </servlet-name>
      <servlet-class> HelloWorldServlet </servlet-class>
   </servlet>
   <servlet-mapping>
      <servlet-name> HelloWorldServlet </servlet-name>
      <url-pattern>/ HelloWorldServlet /*</url-pattern>
   </servlet-mapping>
</web-app>

web.xml

In case of parameters, you can also set these tags in web.xml:

<init-param>
   <param-nam>name</param-name>
   <param-value>nandhu</param-value>
</init-param>

The directory structure that is needed for deploying a servlet is as follows:

HelloWorldServlet
   Web-Inf
      Classes
         HelloWorldServlet.class

Web.xml

In the Weblogic administration console, select Web Application Modules under Deployment and select Deploy a new Web Application Module. Select the directory HelloWorldServlet and click Target Module. Click Deploy. Wait for few seconds until the success message is displayed. Now the servlet is deployed. It can be tested with the following URL: http://hostname:port/HelloWorldServlet/HelloWorldServlet. "Hello world" will be displayed in the browser.

Creating a Web Service from JSP and HTML

JSP is an extensible Web technology that uses template data, custom elements, scripting languages, and server-side Java objects to return dynamic content to a client. Typically, the template data is HTML or XML elements. As HTML/JSP files are autodeployed in Weblogic, just copy the .html/.jsp file into a directory that is already deployed in Weblogic. Any directory can be deployed under the Web Application Module, provided it is of the following format. For example, see the above-mentioned HelloWorldServlet directory structure.

<Directory to be deployed>
   WEB-INF
      Classes
      Web.xml
   *.html
   *.jsp

You can directly access the HTML file by using http://hostname:port/<DirectoryName>/filename.html. For example, http://localhost:7001/TestHtmls/HelloWorld.html.

<%@ page import="java.util.Date"%>
<html>
<body>
The current time is <%= new Date().toString() %>
</body>
</html>

sample.jsp

Creating a Web Service from a Java class file

Follow the steps given below to create a Web service from a Java class. Copy myWebService.java into your directory and compile it.

public class myWebService
{
   public String sayHello(String name)
   {
      if(name==null)
         return "Hello Guest";
      else
         return "Hello " + name;
   }
}

myWebService.java

The servicegen Ant task will create a myWebService.ear file that can be deployed into Weblogic. Run the following Ant task using the command "ant" from the command prompt.

<project name="buildWebservice" default="build-ear">
   <target name="build-ear">
      <servicegen
         destEar="myWebService.ear"
         warName="myWAR.war" 
         contextURI="web_services">
         <service
         javaClassComponents="myWebService"
         targetNamespace="http://www.bea.com/examples"
            serviceName="TraderService"
            serviceURI="/TraderService"
            generateTypes="True"
            expandMethods="True"
               style="RPC">
         </service>
      </servicegen>
   </target>
</project>

build.xml

Once myWebservice.ear is created, deploy it in Weblogic under Deployments->Applications. The URL for accessing this Web service will be http://hostname:portname/servicename. For example, http://localhost:7001/myWebservice/myWebservice.

Note: The style="rpc" attribute specifies that the operations in the Web Service are all RPC-oriented. If the operations in your Web Service are document-oriented, specify style="document" and run the Antbuild.

Conclusion

The real value of Web services lies in the composition of a set of Web services, or what is commonly known as creating a 'flow'. To create a truly versatile business flow suited to every purpose of the target user, Web services have to be developed from various kinds of software components on various technologies, languages, and platforms. The present work addresses the creation of a simple Web service from a variety of J2EE components.

About the Authors

Nandhini Arumugam holds a Masters degree in Computer Applications from PSG College of Technology, Coimbatore. She has worked as a Software Engineer in the Telecom and Mobile Solutions Lab, Hewlett-Packard, Bangalore for more than one year. The domain of her experience includes Web services and J2EE-related technologies. She can be reached at nandhini.arumugam@hp.com.

Sujata De is a Senior Software Engineer for Telecom and Mobile Solutions Lab, Hewlett-Packard, Bangalore. She holdsa Bachelor's degree in Civil Engineering from the Indian Institute of Technology, Kharagpur, followed by Master's degree in Mechanical Engineering from the Indian Institute of Science, Bangalore. She has around three years of industry experience involving quality, Web services, LDAP, UDDI, and J2EE technologies and is currently involved in developing access controllers for Web services. She can be reached at sujata.de@hp.com.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date