< Previous | Next >

Lesson 3: Develop a web bundle that accesses the EJB

About this task

In the previous lesson, you exposed the EJB as an OSGi service. In this lesson, you develop a web bundle that accesses the service. You create the bundle, configure the manifest to import required packages, develop a servlet that accesses the EJB as an OSGi service, and create an HTML page to access the application through a browser.

Creating a web bundle project

About this task

In this section, you create an OSGi bundle with Web 3.0 support and add the bundle to the ConverterApp OSGi application.

Procedure

  1. Open the OSGi bundle project wizard. Click File > New > OSGi Bundle Project. The wizard opens.
  2. Create the project. Enter or select the following values in the wizard:
    Project name
    Web
    Target run time
    WebSphere Application Server v8.5.
    Add Web support (select this check box and select the following value)
    Web 3.0.
    Add bundle to application (select this check box and select the following application)
    ConverterApp
    Create a web bundle project
  3. Click Finish. The project is created.

Configuring the bundle manifest in the web project to import the package from the EJBClient project

About this task

In this section, you add an entry for the com.ibm.example package in the EJBClient project to the Import-Package header in the manifest. The com.ibm.example package contains the interface that you developed for the EJB.

Procedure

  1. Open the manifest. In the web project, double-click Manifest: Web. The manifest editor opens.
  2. Add a dependency to the com.ibm.example package. Click the Dependencies tab. In the Imported Packages section, click Add. The package selection dialog opens. In the Exported Packages field, enter com.ibm.example. Select com.ibm.example from the package list and click OK.
    Add dependency

    The dependency to com.ibm.example is added to the Imported Packages section. Note that because the bundle project is configured with Web 3.0 support, extra import entries for servlet packages such as javax.servlet are already added.

    Imported packages

  3. Save your changes.

Creating a servlet

About this task

In this section, you create an initial servlet with the servlet wizard.

Procedure

  1. Open the servlet wizard. Right-click the web project and select New > Servlet. The servlet wizard opens.
  2. Create the servlet. Enter or select the following values in the wizard:
    Project
    Web
    Java™ package
    com.ibm.example.servlets
    Class name
    ConverterServlet

    Click Finish. The ConverterServlet is created in the web project.

Developing the servlet

About this task

In this section, you develop the servlet and include code to access the EJB as an OSGi service.

Procedure

  1. Open the servlet in the Java editor. If the servlet is not already open in the editor, in the web project, expand the Java Resources/src folder. In the com.ibm.example.servlets package, double-click the ConverterServlet.
  2. Add new import statements. Add the following import statements to the import section at the beginning of the source file:
    import com.ibm.example.EJBConverterLocal;
    import java.io.PrintWriter;
    import java.text.NumberFormat;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
  3. Develop the doGet() method. The servlet contains a basic doGet() method. Replace the auto-generated method with the following method:
    protected void doGet(HttpServletRequest request,
          HttpServletResponse response) throws ServletException, IOException {
    
       PrintWriter w = response.getWriter();
    
       NumberFormat nf = NumberFormat.getInstance();
       nf.setMaximumFractionDigits(2);
    
       try {
          InitialContext context = new InitialContext();
          EJBConverterLocal converter = (EJBConverterLocal) context
                .lookup("osgi:service/" + EJBConverterLocal.class.getName());
    
          String temperature = request.getParameter("temperature");
          if (temperature == null) {
             w.println("<p>A temperature value was not specified.</p>");
          } else if (!temperature.matches("[-+]?[0-9]*\\.?[0-9]+")) {
             w.println("Invalid temperature specified.");
          } else {
             double degrees = Double.parseDouble(temperature);
    
             double celsius = converter.convertToCelsius(degrees);
             w.println("<p>" + temperature + " degrees fahrenheit is "
                   + nf.format(celsius) + " degrees celsius</p>");
    
             double fahrenheit = converter.convertToFahrenheit(degrees);
             w.println("<p>" + temperature + " degrees celsius is "
                   + nf.format(fahrenheit) + " degrees fahrenheit</p>");
          }
    
          w.println("<a href='index.html'>Back</a>");
       } catch (NamingException e) {
          w.println(e.getMessage());
       } catch (NumberFormatException e) {
          w.println("An incorrect temperature was specified");
       }
    }
    Note: Items to note about this code:
    The servlet creates an EJBConverterLocal object called converter. Recall that EJBConverterLocal was the interface you created that contains two temperature conversion methods convertToCelsius() and convertToFahrenheit(). The following line of code handles creation of the object that accesses the EJB as an OSGi service:
    EJBConverterLocal converter = (EJBConverterLocal) context.lookup("osgi:service/" + EJBConverterLocal.class.getName());
    The temperature value to convert is passed to the servlet by the temperature parameter. This value is converted to a Double called degrees, which can be processed by the convertToCelsius() and convertToFahrenheit() methods on the converter object.
    Note: If you want to use remote interfaces, adjust your JNDI lookup code. For example, the context lookup section previously described can be written in the following format:
    EJBConverterRemote converter = (EJBConverterRemote) context.lookup("osgi:service/" + EJBConverterRemote.class.getName() + "/(service.exported.interfaces=*)");
  4. Develop the doPost() method. Replace the auto-generated doPost() method with the following code. Replacing the auto-generated doPost() method ensures that the servlet can be called by both post and get requests from a browser. Calls to doPost() automatically execute the doGet() method.
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	doGet(request, response);
    }
  5. Check your work. The following code is the completed servlet code:
    package com.ibm.example.servlets;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.text.NumberFormat;
    
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.ibm.example.EJBConverterLocal;
    
    @WebServlet("/ConverterServlet")
    public class ConverterServlet extends HttpServlet {
       private static final long serialVersionUID = 1L;
    
       public ConverterServlet() {
          super();
       }
    
       protected void doGet(HttpServletRequest request,
             HttpServletResponse response) throws ServletException, IOException {
    
          PrintWriter w = response.getWriter();
    
          NumberFormat nf = NumberFormat.getInstance();
          nf.setMaximumFractionDigits(2);
    
          try {
             InitialContext context = new InitialContext();
             EJBConverterLocal converter = (EJBConverterLocal) context
                   .lookup("osgi:service/" + EJBConverterLocal.class.getName());
    
             String temperature = request.getParameter("temperature");
             if (temperature == null) {
                w.println("<p>A temperature value was not specified.</p>");
             } else if (!temperature.matches("[-+]?[0-9]*\\.?[0-9]+")) {
                w.println("Invalid temperature specified.");
             } else {
                double degrees = Double.parseDouble(temperature);
    
                double celsius = converter.convertToCelsius(degrees);
                w.println("<p>" + temperature + " degrees fahrenheit is "
                      + nf.format(celsius) + " degrees celsius</p>");
    
                double fahrenheit = converter.convertToFahrenheit(degrees);
                w.println("<p>" + temperature + " degrees celsius is "
                      + nf.format(fahrenheit) + " degrees fahrenheit</p>");
             }
    
             w.println("<a href='index.html'>Back</a>");
          } catch (NamingException e) {
             w.println(e.getMessage());
          } catch (NumberFormatException e) {
             w.println("An incorrect temperature was specified");
          }
       }
    
       protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	doGet(request, response);
    		}
    }
  6. Save your changes.

Creating an HTML file to access the application

About this task

In this section, you create an HTML file, index.html, that contains a form for entering values to submit to the servlet for conversion.

Procedure

  1. Open the new Web page wizard. Right-click the web project and select New > Web Page. The Web page wizard opens.
  2. Create the web page. In the wizard, in the File Name field, enter index.html. In the Template section, select HTML. Click Finish. The page is created and opens in the editor.
    New web page
  3. Select the Source tab of the web page editor.
  4. Update the source. Replace the default source code with the following code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    <title>OSGi EJB Temperature Converter</title>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <script type="text/javascript">
    
    function validate(form) {
    	var temperature = new Number(form.temperature.value);
    	if (isNaN(temperature)) {
    		alert("Please enter a valid number.");
    		return false;
    	}
    	return true;
    }
    
    </script>
    </head>
    <body>
    <form action="ConverterServlet" method="post" onsubmit="return validate(this);">
    	Enter a temperature value:
    	<br/>
    	<input type="text" id="temperature" name="temperature"/>
    	<br/>
    	<br/>
    	<input type="submit" value="Submit"/>
    </form>
    </body>
    </html>

    This HTML contains a form that submits a temperature parameter value to the ConverterServlet. Before it is sent to the servlet, the value to be submitted is validated by the validate() function to ensure that a numerical value was entered.

< Previous | Next >
Icon that indicates the type of topic Tutorial lesson topic
Timestamp icon Last updated: July 17, 2017 21:58

File name: osgi_ejb_3.html