4.4. JSP Web Component Client

The Music EJB can interact with web clients, too. In this section, we'll show you how a JSP client can access the Music Collection database using the same EJB component.

The web component client uses three JSP programs. The first one, musicGet.jsp, displays recording titles and collects user input. Figure 4-5 shows a screen shot of this page.

Figure 4-5. Screen Shot of Initial JSP Web Client Program for the Music EJB


The second JSP program, musicPost.jsp, displays track information for a recording title. Figure 4-6 shows a screen shot after the user selects “Graceland” and clicks the “View Tracks” button.

Figure 4-6. Screen Shot After Clicking the “View Tracks” Button for Recording “Graceland”


The web container invokes the third JSP program, error.jsp, only when a runtime exception is thrown.

musicGet.jsp

This JSP program in Listing 4.8 accesses the Music EJB to read recordings from the Music Collection database. It creates a Music EJB in method jspInit(), which the web container invokes once during JSP initialization. This method also invokes Music EJB business method getMusicList() to read the recording titles. A HttpSession object saves the Music EJB and the ArrayList of RecordingVO objects. The web container invokes JSP musicPost.jsp with the user's recording title selection stored in the request object. The JSP page remembers the selected title by getting it from the session object (it will be null the first time).

Both musicGet.jsp and musicPost.jsp designate error.jsp as the error page in the JSP page directive errorPage. If a runtime exception occurs, the web container invokes the JSP's error page and makes the implicit object exception available within the error page.

Listing 4.8. musicGet.jsp
<%--
  musicGet.jsp
--%>

<%--
  JSP web component to read the Music Collection Database
  using the Music EJB stateless session bean.
  Place recording titles inside an HTML select component.
  When user clicks the "View Tracks" button,
  invoke musicPost.jsp to display the track information.
--%>

<%--
  The following page directive tells the JSP engine to
  import the named classes and packages when compiling
  the generated servlet code and to use "error.jsp"
  for an errorPage.
--%>

<%@ page import="Music,MusicHome,RecordingVO,java.util.*,
javax.naming.Context, javax.naming.InitialContext,
javax.rmi.PortableRemoteObject" errorPage="error.jsp" %>

<%--
  The following 3 variables appear in a JSP declaration.
  They appear outside the generated _jspService() method,
  which gives them class scope.

  Since we want to initialize our Music EJB object once
  and read the Music Collection database to get the
  recording titles once, we place this code inside
  method jspInit().
  The EJB business method getMusicList()
  returns a collection of RecordingVO objects which we
  store in ArrayList albums.
--%>
<%!
  MusicHome musicHome;
  Music mymusic;
  ArrayList albums;

  public void jspInit() {
    try {
      Context initial = new InitialContext();
      Object objref = initial.lookup(
                   "java:comp/env/ejb/EJBMusic");
      musicHome = (MusicHome)PortableRemoteObject.narrow(
          objref, MusicHome.class);
      mymusic = musicHome.create();
      albums = mymusic.getMusicList();

    } catch (Exception ex) {
      System.out.println("Unexpected Exception: " +
           ex.getMessage());
      ex.printStackTrace();
    }
  }
%>

<%--
  The following scriptlet accesses the implicit
  request object to obtain the current URL and
  saves it to the session object for later retrieval.
  It also saves variable mymusic, so we can
  make remote calls to our Music EJB, and the collection of
  RecordingVO objects. These variables will all be
  available to other pages within the session.
--%>

<%
  String requestURI = request.getRequestURI();
  session.putValue("url", requestURI);
  session.putValue("mymusic", mymusic);
  session.putValue("albums", albums);
%>
<%--
  The following html code sets up the page to display
  the recording titles in a select element and invokes
  page musicPost.jsp with the selected user input.
--%>

<html>
<head>
<title>Music Collection Database Using EJB & JSP</title>
</head>
<body bgcolor=white>
<h1><b><center>Music Collection Database Using EJB & JSP</center></b></h1>
<hr>
<p>
There are <%= albums.size() %> recordings.

<form method="post" action="musicPost.jsp">
<p>
Select Music Recording:
<select name="TITLE">

<%
  // Generate html <option> elements with the recording
  // titles stored in each RecordingVO element.
  // Obtain the current title from the session object
  // (this will be null the first time).

  String title;
  String currentTitle =
         (String)session.getValue("curTitle");
  if (currentTitle == null) currentTitle = "";
  RecordingVO r;
  Iterator i = albums.iterator();

  while (i.hasNext()) {
    r = (RecordingVO)i.next();
    title = r.getTitle();

    if (title.equals(currentTitle)) {
      out.println("<option selected>" + title
             + "</option>");
    }
    else {
      out.println("<option>" + title + "</option>");
    }
  }
%>
</select><p><p>

<%--
  Provide a "View Tracks" button to submit
  the requested title to page musicPost.jsp
--%>

<input TYPE="submit" NAME="View" VALUE="View Tracks">
</form>
</body>
</html>

musicPost.jsp

The web container invokes musicPost.jsp when a user submits a recording title request. The title comes from the request object and the session object contains the Music EJB and the ArrayList of RecordingVO objects. Listing 4.9 shows the code.

In this program we'll search the ArrayList collection in a loop looking for the RecordingVO object with a matching title. When we find it, a call to getTrackList() from the Music EJB obtains the track list for that recording. Now we can display track information in an HTML table with three columns: the track number, the track length, and the track title.

Listing 4.9. musicPost.jsp
<%--
  musicPost.jsp
--%>

<%--
  JSP web component to display the track information
  for the selected recording passed in the session object.
  We obtain the track information by calling the
  Music EJB's getTrackList() business method.
--%>
<%--
  Use a page directive to import needed classes and
  packages for compilation.
  Specify "error.jsp" as the page's errorPage.
--%>

<%@ page import="Music,MusicHome,
RecordingVO,TrackVO,java.util.*, javax.naming.Context, javax.naming.InitialContext,
javax.rmi.PortableRemoteObject" errorPage="error.jsp" %>

<%--
  Declare the class variables.
--%>

<%!
  Music mymusic;
  ArrayList albums;
%>

<%--
  The following scriptlet accesses the session
  object to assign values to requestURI, mymusic,
  and albums. It obtains the user selected title
  from the request object and stores it into the
  session object to be used by the request page
  as the new default.
--%>

<%
  ArrayList tracks;
  String requestURI = (String)session.getValue("url");
  mymusic = (Music)session.getValue("mymusic");
  albums = (ArrayList)session.getValue("albums");
  String currentTitle = request.getParameter("TITLE");
  session.putValue("curTitle", currentTitle);
%>

<html>
<head>
<title><%= currentTitle %> View Tracks</title>
</head>
<body bgcolor=white>
<h1><b><center>Music Collection Database Using EJB & JSP</center></b></h1>
<hr><p>

<%
  // Access the albums ArrayList to find the RecordingVO
  // object with the selected title.
  RecordingVO r = null;
  Iterator i = albums.iterator();
  boolean found = false;

  while (i.hasNext()) {
    r = (RecordingVO)i.next();
    if (r.getTitle().equals(currentTitle)) {
      found = true;
      break;
    }
  }

  if (found) {            // found title
    // Access the MusicEJB to read the Music Collection
    // database and get the track list for the
    // selected recording
    tracks = mymusic.getTrackList(r);
%>

<%--
  Set up an html table to hold the data.
--%>

    <table bgcolor=#e0e0e0 border=2 cellpadding=5>
    <caption><h2>
    <%= "Tracks for " + currentTitle %>
    </h2></caption>
    <tr>
    <th>Track Number</th>
    <th>Track Length</th>
    <th>Track Title</th>
    </tr>
<%
    // Use a combination of scriptlet code,
    // html and JSP expressions to build the table
    TrackVO t;
    i = tracks.iterator();
    while (i.hasNext()) {
      t = (TrackVO)i.next();
%>

      <tr>
      <td> <%= t.getTrackNumber() %></td>
      <td> <%= t.getTrackLength() %></td>
      <td> <%= t.getTitle() %></td>
      </tr>

<%
    }
    out.println("</table>");
  }
  else {
    out.println("No tracks for " + currentTitle
           + " found.<br>");
  }
%>

<%--
  Provide a dynamic link to the request page so
  the user can request another track list to display.
--%>

<br><br><a href="<%= requestURI %>">Return to Main Page</a>
</body>
</html>

error.jsp

The JSP engine can recognize a JSP file as an error page. When an exception is thrown, the web container invokes the error page. A JSP file is an error page if the JSP page directive isErrorPage is set to true.

The implicit exception object (an instance of class java.lang.Throwable) is available only in error pages. This object refers to the runtime exception that caused the error page to be invoked. In Listing 4.10 for error.jsp, we call the printStackTrace() method with class exception to display the exception object's stack trace in an HTML table. The <pre> and </pre> tags maintain formatting of the stack trace.

Listing 4.10. error.jsp
<%--
  error.jsp
--%>

<%@ page isErrorPage="true" import="java.io.*" %>

<html>
<head>
<title>Error Page</title>
</head>
<body>
<h1>You Have Encountered an Error</h1>

<table border="1">
  <tr>
    <td><b><font size="+1">Stack Trace</font></b></td>
  </tr>
  <tr>
    <td><pre>

<%
  StringWriter sw = new StringWriter();
  PrintWriter pw = new PrintWriter(sw);
  exception.printStackTrace(pw);
  out.println(sw);
%>

    </pre></td>
  </tr>
</table>
</body>
</html>

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.145.109