<?xml version="1.0" encoding="UTF-8"?>
<section version="5.0" xml:id="web.component" xml:lang="en"
         xmlns="http://docbook.org/ns/docbook"
         xmlns:xlink="http://www.w3.org/1999/xlink"
         xmlns:xi="http://www.w3.org/2001/XInclude"
         xmlns:svg="http://www.w3.org/2000/svg"
         xmlns:mml="http://www.w3.org/1998/Math/MathML"
         xmlns:html="http://www.w3.org/1999/xhtml"
         xmlns:db="http://docbook.org/ns/docbook">
  <info>
    <title>Developing Web Components</title>
  </info>

  <section xml:id="webcomponent.intro">
    <info>
      <title>Introduction</title>
    </info>

    <para>A Web Component is a generic term which denotes both JSP pages and
    Servlets. Web components are packaged in a <code> .war </code> file and
    can be deployed in a JOnAS server via the web container service. Web
    components can be integrated in a J2EE application by packing the <code>
    .war </code> file in an <code> .ear </code> file (refer to the <link
    xlink:href="j2eeprogrammerguide#j2ee.appAss"> J2EE Application
    Programmer's Guide </link> ).</para>

    <para>The JOnAS distribution includes a Web application example: <code>
    The EarSample example. </code></para>

    <para>The directory structure of this application is the following:</para>

    <informaltable>
      <tgroup cols="2">
        <tbody>
          <row>
            <entry>etc/xml</entry>

            <entry>contains the web.xml file describing the web
            application</entry>
          </row>

          <row>
            <entry>etc/resources/web</entry>

            <entry>contains html pages and images; JSP pages can also be
            placed here.</entry>
          </row>

          <row>
            <entry>src/java/org/ow2/jonas/examples/ear/web</entry>

            <entry>servlet sources</entry>
          </row>

          <row>
            <entry>src/java/org/ow2/jonas/examples/ear/(!web)</entry>

            <entry>beans sources (Session, Message Driven, JPA Entity)</entry>
          </row>
        </tbody>
      </tgroup>
    </informaltable>

    <para>The bean directory is not needed if beans coming from another
    application will be used.</para>
  </section>

  <section xml:id="webcomponent.jsp">
    <info>
      <title>The JSP pages</title>
    </info>

    <para>Java Server Pages (JSP) is a technology that allows regular, static
    HTML, to be mixed with dynamically-generated HTML written in Java
    programming language for encapsulating the logic that generates the
    content for the page. Refer to the <link
    xlink:href="http://java.sun.com/products/jsp/"> <trademark>Java Server
    Pages</trademark></link> and the <link
    xlink:href="http://java.sun.com/products/jsp/docs.html"> Quickstart guide
    </link> for more details.</para>

    <section>
      <info>
        <title>Example:</title>
      </info>

      <para>The following example shows a sample JSP page that lists the
      content of a cart.</para>

      <screen>
    &lt;!-- Get the session --&gt;
    &lt;%@ page session="true" %&gt;

    &lt;!-- The import to use --&gt;
    &lt;%@ page import="java.util.Enumeration" %&gt;
    &lt;%@ page import="java.util.Vector"      %&gt;

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

        &lt;!-- Each iteration of the loop display a line of the table --&gt;
        &lt;%
          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();
        %&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;%=prod.getReference()%&gt;&lt;/td&gt;
          &lt;td&gt;&lt;%=prod.getName()%&gt;&lt;/td&gt;
          &lt;td&gt;&lt;%=prod.getPrice()%&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;%
        } // end loop
        %&gt;
      &lt;/table&gt;
    &lt;/body&gt;
    &lt;/html&gt;</screen>

      <para>It is a good idea to hide all the mechanisms for accessing EJBs
      from JSP pages by using a proxy java bean, referenced in the JSP page by
      the <code> usebean </code> special tag. This technique is shown in the
      <code> alarm example </code> , where the .jsp files communicate with the
      EJB via a proxy java bean <code> ViewProxy.java </code> .</para>
    </section>
  </section>

  <section xml:id="webcomponent.servlet">
    <info>
      <title>The Servlets</title>
    </info>

    <para>Servlets are modules of Java code that run in an application server
    for answering client requests. Servlets are not tied to a specific
    client-server protocol. However, they are most commonly used with HTTP,
    and the word "Servlet" is often used as referring to an "HTTP
    Servlet."</para>

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

    <para>Typical uses for HTTP Servlets include:</para>

    <itemizedlist>
      <listitem>
        <para>processing and/or storing data submitted by an HTML form,</para>
      </listitem>

      <listitem>
        <para>providing dynamic content generated by processing a database
        query,</para>
      </listitem>

      <listitem>
        <para>managing information of the HTTP request.</para>
      </listitem>
    </itemizedlist>

    <para>For more details refer to the <link
    xlink:href="http://java.sun.com/products/servlet/">
    <trademark>Java</trademark> Servlet Technology </link> and the <link
    xlink:href="http://java.sun.com/docs/books/tutorial/servlets/TOC.html">
    Servlets tutorial </link> .</para>

    <section>
      <info>
        <title>Example:</title>
      </info>

      <para>The following example is a sample of a Servlet that lists the
      content of a cart. This example is the servlet version of the previous
      JSP page example.</para>

      <screen>
    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("&lt;html&gt;&lt;head&gt;&lt;title&gt;Your cart&lt;/title&gt;&lt;/head&gt;");
            out.println("&lt;body&gt;");
            out.println("&lt;h1&gt;Content of your cart&lt;/h1&gt;&lt;br&gt;");
            out.println("&lt;table&gt;");

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

            // 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("&lt;tr&gt;");
                out.println("&lt;td&gt;" + prodId + &lt;/td&gt;);
                out.println("&lt;td&gt;" + prodName + &lt;/td&gt;);
                out.println("&lt;td&gt;" + prodPrice + &lt;/td&gt;);
                out.println("&lt;/tr&gt;");
            }

            out.println("&lt;/table&gt;");
            out.println("&lt;/body&gt;");
            out.println("&lt;/html&gt;");
            out.close();
        }
    }</screen>
    </section>
  </section>

  <section xml:id="webcomponent.ejb">
    <info>
      <title>Accessing an EJB from a Servlet or JSP page</title>
    </info>

    <para>Through the JOnAS web container service, it is possible to access an
    enterprise java bean and its environment in a J2EE-compliant way.</para>

    <para>The following sections describe:</para>

    <orderedlist>
      <listitem>
        <para>How to access the Remote Home interface of a bean.</para>
      </listitem>

      <listitem>
        <para>How to access the Local Home interface of a bean.</para>
      </listitem>

      <listitem>
        <para>How to access the environment of a bean.</para>
      </listitem>

      <listitem>
        <para>How to start transactions in servlets.</para>
      </listitem>
    </orderedlist>

    <para>Note that all the following code examples are taken from the <code>
    The EarSample example </code> provided in the JOnAS distribution.</para>

    <section>
      <info>
        <title>Accessing the Remote Home interface of a bean:</title>
      </info>

      <para>In this example the servlet gets the Remote Home interface OpHome
      registered in JNDI using an EJB reference, then creates a new instance
      of the session bean:</para>

      <screen>
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("&lt;li&gt;Cannot get initial context for JNDI: ");
            out.println(e + "&lt;/li&gt;");
            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("&lt;li&gt;Cannot lookup java:comp/env/ejb/Op: " + e + "&lt;/li&gt;");
            return;
        }
        // OpBean creation
        Op op = null;
        try {
            op = opHome.create("User1");
        } catch (Exception e) {
            out.println("&lt;li&gt;Cannot create OpBean: " + e + "&lt;/li&gt;");
            return;
        }</screen>

      <para>Note that the following elements must be set in the <code> web.xml
      </code> file tied to this web application:</para>

      <screen>
  &lt;ejb-ref&gt;
    &lt;ejb-ref-name&gt;ejb/Op&lt;/ejb-ref-name&gt;
    &lt;ejb-ref-type&gt;Session&lt;/ejb-ref-type&gt;
    &lt;home&gt;org.objectweb.earsample.beans.secusb.OpHome&lt;/home&gt;
    &lt;remote&gt;org.objectweb.earsample.beans.secusb.Op&lt;/remote&gt;
    &lt;ejb-link&gt;secusb.jar#Op&lt;/ejb-link&gt;
  &lt;/ejb-ref&gt;</screen>
    </section>

    <section>
      <info>
        <title>Accessing the Local Home of a bean:</title>
      </info>

      <para>The following example shows how to obtain a local home interface
      OpLocalHome using an EJB local reference:</para>

      <screen>
//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("&lt;li&gt;Cannot lookup java:comp/env/ejb/OpLocal: " + e + "&lt;/li&gt;");
            return;
        }</screen>

      <para>This is found in the <code> web.xml </code> file:</para>

      <screen>
  &lt;ejb-local-ref&gt;
    &lt;ejb-ref-name&gt;ejb/OpLocal&lt;/ejb-ref-name&gt;
    &lt;ejb-ref-type&gt;Session&lt;/ejb-ref-type&gt;
    &lt;local-home&gt;org.objectweb.earsample.beans.secusb.OpLocalHome&lt;/local-home&gt;
    &lt;local&gt;org.objectweb.earsample.beans.secusb.OpLocal&lt;/local&gt;
    &lt;ejb-link&gt;secusb.jar#Op&lt;/ejb-link&gt;
  &lt;/ejb-local-ref&gt;</screen>
    </section>

    <section>
      <info>
        <title>Accessing the environment of the component:</title>
      </info>

      <para>In this example, the servlet seeks to access the component's
      environment:</para>

      <screen>
       String envEntry = null;
        try {
            envEntry = (String) initialContext.lookup("java:comp/env/envEntryString");
        } catch (Exception e) {
            out.println("&lt;li&gt;Cannot get env-entry on JNDI " + e + "&lt;/li&gt;");
            return;
        }</screen>

      <para>This is the corresponding part of the <code> web.xml </code>
      file:</para>

      <screen>
  &lt;env-entry&gt;
    &lt;env-entry-name&gt;envEntryString&lt;/env-entry-name&gt;
    &lt;env-entry-value&gt;This is a string from the env-entry&lt;/env-entry-value&gt;
    &lt;env-entry-type&gt;java.lang.String&lt;/env-entry-type&gt;
  &lt;/env-entry&gt;</screen>
    </section>

    <section>
      <info>
        <title>Starting transactions in servlets:</title>
      </info>

      <para>The servlet wants to start transactions via the UserTransaction
      :</para>

      <screen>
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("&lt;li&gt;Cannot lookup java:comp/UserTransaction: " + e + "&lt;/li&gt;");
            return;
        }

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

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