Developing Web Components

Target Audience and Content

The target audience for this guide is the Web Component provider, i.e. the person in charge of developing the web components on the server side.

The content of this guide is the following:

  1. Target Audience and Content
  2. Introduction
  3. The JSPs
  4. The Servlets
  5. Accessing an EJB from a Servlet or JSP page

Introduction

A Web Component is a generic term which specifies both JSP pages and Servlets. Web components are packaged in a .war file and may be deployed in a JOnAS server via the web service. Web components may be integrated in a J2EE application by packing the .war file in a .ear file (see J2EE Application Programmer's Guide).

You can find a Web application exemple in the JOnAS distribution: The EarSample example

The directory structure of this application looks like this:

etc/xmlcontains the web.xml file describing the web application.
etc/resources/webcontains html pages and images ; JSP pages can also be placed here.
src/org/objectweb/earsample/servletsservlet sources,
src/org/objectweb/earsample/beansbeans sources

In case your beans come from another application, you don't need the bean directory.

The JSP pages

Java Server Pages (JSP) is a technology that lets you mix regular, static HTML, with dynamically-generated HTML written in Java programming language to encapsulate the logic that generates the content for the page. For more details see Java Server PagesTM and Quickstart guide.

Example:

The following example shows a sample JSP page which lists the content of a cart.

    <!-- Get the session -->
    <%@ page session="true" %>

    <!-- The import to use -->
    <%@ page import="java.util.Enumeration" %>
    <%@ page import="java.util.Vector"      %>

    <html>
    <body bgcolor="white">
      <h1>Content of your cart</h1><br>
      <table>
        <!-- The header of the table -->
        <tr bgcolor="black">
          <td><font color="lightgreen">Product Reference</font></td>
          <td><font color="lightgreen">Product Name</font></td>
          <td><font color="lightgreen">Product Price</font></td>
        </tr>

        <!-- Each iteration of the loop display a line of the table -->
        <%
          Cart cart = (Cart) session.getAttribute("cart");
          Vector products = cart.getProducts();
          Enumeration enum = products.elements();
          // loop through the enumeration
          while (enum.hasMoreElements()) {
              Product prod = (Product) enum.nextElement();
        %>
        <tr>
          <td><%=prod.getReference()%></td>
          <td><%=prod.getName()%></td>
          <td><%=prod.getPrice()%></td>
        </tr>
        <%
        } // end loop
        %>
      </table>
    </body>
    </html>
    

It could be a good idea to hide all the mechanisms to access EJBs from JSP pages by using a proxy java bean, refered in the JSP page by the usebean special tag. This technique is shown in the alarm example. Just look at one of the .jsp files. A proxy java bean ViewProxy.java has been used to contain the glue necessary to access EJB.

The Servlets

Servlets are modules of Java code that run in an application server to answer client requests. Servlets are not tied to a specific client-server protocol but they are most commonly used with HTTP and the word "Servlet" is often used in the meaning of "HTTP Servlet".

Servlets make use of the Java standard extension classes in the packages javax.servlet (the basic Servlet framework) and javax.servlet.http (extensions of the Servlet framework for Servlets that answer HTTP requests).

Typical uses for HTTP Servlets include:

For more details see JavaTM Servlet Technology and Servlets tutorial.

Example:

The following example shows a sample of a Servlet which lists the content of a cart.
This example is the servlet version of the previous JSP page example

    import java.util.Enumeration;
    import java.util.Vector;
    import java.io.PrintWriter;
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;

    public class GetCartServlet extends HttpServlet {

        protected void doGet(HttpServletRequest req, HttpServletResponse res)
                             throws ServletException, IOException {

            res.setContentType("text/html");
            PrintWriter out = res.getWriter();

            out.println("<html><head><title>Your cart</title><head>");
	    out.println("<body>");
	    out.println("<h1>Content of your cart</h1><br>");
	    out.println("<table>");

            // The header of the table
	    out.println("<tr>");
            out.println("<td><font color="lightgreen">Product Reference</font></td>");
	    out.println("<td><font color="lightgreen">Product Name</font></td>");
	    out.println("<td><font color="lightgreen">Product Price</font></td>");
            out.println("</tr>");

            // Each iteration of the loop display a line of the table
            HttpSession session = req.getSession(true);
            Cart cart = (Cart) session.getAttribute("cart");
	    Vector products = cart.getProducts();
	    Enumeration enum = products.elements();
	    while (enum.hasMoreElements()) {
	        Product prod = (Product) enum.nextElement();
	        int prodId = prod.getReference();
                String prodName = prod.getName();
                float prodPrice = prod.getPrice();
	        out.println("<tr>");
	        out.println("<td>" + prodId + </td>);
	        out.println("<td>" + prodName + </td>);
	        out.println("<td>" + prodPrice + </td>);
	        out.println("</tr>");
            }

	    out.println("</table>");
	    out.println("</body>");
            out.println("</html>");
            out.close();
        }
    }
    

Accessing an EJB from a Servlet or JSP page

Since JOnAS2.6 and its web container service it is possible to access to an enterprise java bean and its environment in a J2EE compliant way.

Here we show :

  1. How to access the Remote Home interface of a bean
  2. How to access the Local Home interface of a bean
  3. How to access the environment of a bean
  4. How to start transactions in servlets
Note that all part of code are taken from the The EarSample example provided in the JOnAS distribution.

Accessing the Remote Home interface of a bean:

In this example the servlet gets the Remote Home interface OpHome registered in JNDI using an EJB reference, and then creates a new instance of the session bean:
import javax.naming.Context;
import javax.naming.InitialContext;

//remote interface
import org.objectweb.earsample.beans.secusb.Op;
import org.objectweb.earsample.beans.secusb.OpHome;

        Context initialContext = null;
        try {
            initialContext = new InitialContext();
        } catch (Exception e) {
            out.print("<li>Cannot get initial context for JNDI: ");
            out.println(e + "</li>");
            return;
        }
      // Connecting to OpHome thru JNDI
        OpHome opHome = null;
        try {
            opHome = (OpHome) PortableRemoteObject.narrow(initialContext.lookup("java:comp/env/ejb/Op"), OpHome.class);
        } catch (Exception e) {
            out.println("<li>Cannot lookup java:comp/env/ejb/Op: " + e + "</li>");
            return;
        }
        // OpBean creation
        Op op = null;
        try {       
            op = opHome.create("User1"); 
        } catch (Exception e) {
            out.println("<li>Cannot create OpBean: " + e + "</li>");
            return;
        }
Note that you have to set in the web.xml file tied to this web application the following elements:

  <ejb-ref>
    <ejb-ref-name>ejb/Op</ejb-ref-name>
    <ejb-ref-type>Session</ejb-ref-type>
    <home>org.objectweb.earsample.beans.secusb.OpHome</home>
    <remote>org.objectweb.earsample.beans.secusb.Op</remote>
    <ejb-link>secusb.jar#Op</ejb-link>
  </ejb-ref>

Accessing the Local Home of a bean:

Here we show how to get a local home interface OpLocalHome using an EJB local reference:

//local interfaces
import org.objectweb.earsample.beans.secusb.OpLocal;
import org.objectweb.earsample.beans.secusb.OpLocalHome;


      // Connecting to OpLocalHome thru JNDI
        OpLocalHome opLocalHome = null;
        try {
            opLocalHome = (OpLocalHome) 
                initialContext.lookup("java:comp/env/ejb/OpLocal");
        } catch (Exception e) {
            out.println("<li>Cannot lookup java:comp/env/ejb/OpLocal: " + e + "</li>");
            return;
        }
Here you will find in the web.xml file:
  <ejb-local-ref>
    <ejb-ref-name>ejb/OpLocal</ejb-ref-name>
    <ejb-ref-type>Session</ejb-ref-type>
    <local-home>org.objectweb.earsample.beans.secusb.OpLocalHome</local-home>
    <local>org.objectweb.earsample.beans.secusb.OpLocal</local>
    <ejb-link>secusb.jar#Op</ejb-link>
  </ejb-local-ref>

Accessing the environment of the component:

Here the servlet wants to access the component's environment:
       String envEntry = null;
        try {
            envEntry = (String) initialContext.lookup("java:comp/env/envEntryString");
        } catch (Exception e) {
            out.println("<li>Cannot get env-entry on JNDI " + e + "</li>");
            return;
        }
Here is the corresponding part of web.xml file:

  <env-entry>
    <env-entry-name>envEntryString</env-entry-name>
    <env-entry-value>This is a string from the env-entry</env-entry-value>
    <env-entry-type>java.lang.String</env-entry-type>
  </env-entry>

Starting transactions in servlets:

The servlet wants to start transaction via the UserTransaction:
import javax.transaction.UserTransaction;

       // We want to start transactions from client: get UserTransaction
        UserTransaction utx = null;
        try {
            utx = (UserTransaction) initialContext.lookup("java:comp/UserTransaction");
        } catch (Exception e) {
            out.println("<li>Cannot lookup java:comp/UserTransaction: " + e + "</li>");
            return;
        }

        try { 
            utx.begin();
            opLocal.buy(10);
            opLocal.buy(20); 
            utx.commit();

        } catch (Exception e) {
            out.println("<li>exception during 1st Tx: " + e + "</li>");
            return;
        }