Skip Headers
Oracle® Containers for J2EE Enterprise JavaBeans Developer's Guide
10g (10.1.3.5.0)

Part Number E13981-01
Go to Documentation Home
Home
Go to Book List
Book List
Go to Table of Contents
Contents
Go to Index
Index
Go to Feedback page
Contact Us

Go to previous page
Previous
Go to next page
Next
View PDF

Accessing a Web Service From an Enterprise Bean

From within an enterprise bean, you can obtain a Web service and invoke its methods.

Using EJB 3.0, you can use annotations and resource injection (see "Using Annotations") without having to create an environment reference for the Web service.

Using EJB 2.1, you must use the initial context (see "Using Initial Context") and you must create an environment reference for the Web service (see "Configuring an Environment Reference to a Web Service") before you can look it up.

For more information, see "Assembling a J2EE Web Service Client " in the Oracle Application Server Web Services Developer's Guide.

Using Annotations

Given the Web service that Example 30-3 shows, you can access the Web service from an EJB 3.0 stateless session bean using resource injection, as Example 30-4 shows.

Example 30-3 Annotating a Web Service

import javax.jws.WebService;
import javax.jws.WebMethod;

@WebService
public class StockQuoteProvider {

    @WebMethod
    public Float getLastTradePrice() {
        ...
    }
}

Example 30-4 Calling Out to a Web Service Obtained by Resource Injection

@Stateless 
public class InvestmentBean implements Investment {

    public void checkPortfolio(...) {
        ...
        @Resource StockQuoteProvider sqp;

        // Get a quote
        Float quotePrice = sqp.getLastTradePrice(...);
        ...
    }
}

Using Initial Context

After you define an environment reference to a Web service (see "Configuring an Environment Reference to a Web Service"), you can use the initial context to look up the Web service and invoke its methods from within your stateless session bean, as Example 30-5 shows.

Example 30-5 Calling Out to a Web Service Obtained from the Initial Context

@Stateless 
public class InvestmentBean implements Investment {

    public void checkPortfolio(...) {
        ...
        // Obtain the default initial JNDI context
        Context initCtx = new InitialContext();
        // Look up the stock quote service in the environment
        com.example.StockQuoteService sqs = (com.example.StockQuoteService)initCtx.lookup(
            "java:comp/env/service/StockQuoteService");
        // Get the stub for the service endpoint
        com.example.StockQuoteProvider sqp = sqs.getStockQuoteProviderPort();
        // Get a quote
        float quotePrice = sqp.getLastTradePrice(...);
        ...
    }
}