Tuesday, December 12, 2006

Web.xml to configure your Java Web Service

This blog describes how to configure your Java Web Service. Specifically, how to initialize your Java Web Service. In this article I assume you have used Sun Java Studio Enterprise 8 to create your RPC based web service.

Add the following lines to the top of you web service class. Typically this class ends in Impl. Your web service class needs to implement ServiceLifecycle. The example below shows how to read the init param called MyParam that is in web.xml.

import javax.xml.rpc.server.*;
import javax.xml.rpc.*;

public class MyDemoWSImpl implements MyDemoWSSEI, ServiceLifecycle {

     // store the servletContext here since we can only get it when the applet starts up.
     private ServletContext servletContext;

     // Required by ServiceLifecycle interface
     // This is only called once when the web service is started.
     // This is NOT called everytime a web method is called
     public void init(Object context) throws ServiceException
          // get the servlet context
          // This is where the General context parameters (aka init parameters) of the web.xml are stored.
          ServletEndpointContext soapContext = (ServletEndpointContext) context;
          servletContext = soapContext.getServletContext();

     // Required by ServiceLifecycle interface
     public void destroy()

     public String MyParam() throws Exception
          return GetInitParam("MyParam");



To add and specify the value for MyParam in web.xml you need to find you web.wml file. It is typically in the Web Pages\Web-INF\web.xml path if you are using BluePrints type project in Sun Java Studio Enterprise 8. You can type the entry in web.xml as shown below or you can just double click the web.xml file and use the Sun Java Studio Enterprise 8 editor. The editor has tabs. Click on the General tab if it is not already selected. Expand the Context Parameters section, then click the Add button. Type in MyParam as the Param Name, some value as Param Value, and Description is a description of what the param is or what it is for (whatever you want to put there, it is just for documentation purposes).

Here is web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <description>MyParam description for documentation</description>
    <param-value>the value of MyParam</param-value>

No comments: