Sun ONE logo     Previous      Contents      Index      Next     
Sun ONE Application Server 7, Standard Edition Sun[tm] ONE Studio 4, Enterprise Edition for Java[tm] with Application Server 7 Tutorial



Developing Session Beans and Web Applications

In this exercise you will create a simple stateless session bean and a web front end using the IDE. After testing the session bean, you will compose a J2EE[tm] application, verify that the application works properly, modify several components in the application and then step through various parts of the application using the IDE's debugging facilities.

Proceed to Becoming Familiar with the Sample for a brief introduction to the sample application prior to deploying and exercising it.

Becoming Familiar with the Sample

If you are already familiar with the JDBC[tm] Simple sample application (it is the sample used in Getting Started with Sun ONE Application Server 7), proceed to the next section, Creating a Session Bean with the EJB[tm] Builder.

The sample application that you will be using during this exercise consists of a web application module and an EJB module containing a single stateless session bean. The web and EJB modules are packaged in an Enterprise Application Archive (EAR) file. Although patterned after basic "Hello World" applications, this sample displays a greeting based on the user's input and the time of day. Since each greeting is recorded to a database table, the user also has the option to list all previously generated greetings.

The display greeting path through the application is represented by the yellow numbered steps in the following diagram while the greeting log display path through the application is represented by the lettered blue steps in the diagram.


Diagram showing flow between  jdbc-simple.war internals,  jdbc-simpleEjb.jar, greeting log table, and browser Client

When the user accesses the application, the first page of the application prompts the user to enter a name that will be displayed in a subsequent greeting page.


Screen shot of JBDC-SIMPLE Sample Application  start page for user name entry

After entering a name and clicking on the Process button, the following page is displayed with the appropriate greeting for the time of day.

In the background, the GreeterDBServlet accessed the stateless session bean to determine the appropriate greeting ("morning", "afternoon" or "evening"). The GreeterDBServlet sets the appropriate greeting message in the request object of the servlet request and specifies a JavaServer Pages[tm] page to display the result.


Screen shot of JDBC-Simple Sample Application\xd5 s greeting page reflecting user name entered

The greeting is displayed. When the user elects to list all previously generated greetings, the GreeterDBLogDisplayServlet performs a select all on the database table of greetings and specifies a JSP[tm] page to display the result


Screen shot showing JDBC-Simple Database Log display

Proceed to Creating a Session Bean with the EJB[tm] Builder to create the stateless session bean from scratch.

Creating a Session Bean with the EJB[tm] Builder

The session bean that you will create is called GreeterDB. It generates a greeting message based on the current time upon request.

  1. Create the Session Bean
  2. Modify JNDI Name
  3. Modify Automatically Generated Methods
  4. Create a Business Method

Create the Session Bean

To create the session bean using the IDE's EJB Builder facility:

  1. In the IDE, click the Explorer window's Filesystems tab.
  2. Select the Filesystems node, right-click, select Mount -> Local Directory.
  3. The New Wizard - Local Directory window is displayed.

  4. Navigate to the IDE user directory that you specified during the first startup of the IDE:
  5. <ide_user_dir>/sampledir/examples

    For example:

    C:\ide-userdir\sampledir\examples

    The user directory is automatically created when you start the IDE for the first time. You may have specified a different base user directory than presented in this example, but the sampledir directory is created automatically.

  6. Click the Create New Folder icon in the upper left hand portion of the window.
  7. A folder named New Folder appears.

  8. Click on the New Folder item and enter the name "jdbc".
  9. Double click the newly named "jdbc" directory and create a new folder named "mysimple" under this directory.
  10. Repeat this operation to create a directory named "src" under the mysimple directory.
  11. Click once on the "src" directory and click the Finish button.
  12. The newly created jdbc/mysimple/src directory appears as a mounted filesystem in the Explorer window.


Screen shot showing mysimplerc in the Filesystems tab

  1. Right-click the new filesystem and choose New -> Java Package.
  2. You will use this Java package to hold the EJB source code of the application.

  3. Name the new Java package:
  4. samples.jdbc.simple.ejb

    Click Finish.

    A new directory named samples/jdbc/simple/ejb appears under the mysimple/src filesystem.

  1. Right-click the ejb directory node and choose New -> J2EE -> Session EJB.
  2. The Session Bean Name and Properties pane of the New Wizard is displayed.

  3. Type GreeterDB in the EJB Name field and click Finish.
  4. The default settings are used when creating the session bean and then the GreeterDB session bean is displayed in the Explorer window.

    Note the presence of a new GreeterDB (EJB) node and three other nodes:


Screen shot showing GreeterDB(EJB) under ejb in Filesystems window

The GreeterDB (EJB) node is a logical representation of the session bean while the three other nodes represent the class files of the remote, implementation and home interfaces. The IDE creates the minimal set of required methods in the EJB implementation class file.

Modify JNDI Name

To avoid the possibility of naming conflicts with previously deployed versions of the JDBC Simple application, you need to modify the JNDI Name of the EJB.

  1. Right-click the GreeterDB (EJB) node and select Properties.
  2. Select the Sun ONE AS tab.
  3. Enter ejb/my-jdbc-simple in the JNDI Name field.
  4. Close the Properties window.

This JNDI name will uniquely identify this EJB throughout the application server instance to which the EJB is deployed.

Modify Automatically Generated Methods

Your next step is to enhance the automatically generated methods of the session bean. These modifications will result in output being written to the stdout stream when each standard method is invoked by the EJB container of the application server. Since output written to stdout is automatically redirected to the application server's event log, you will see this output in the server's log file when you test the session bean.

To update methods:

  1. Double-click the GreeterDBBean node that represents the implementation class of the session bean.
  2. The source editor shows the GreeterDBBean.java file.

  3. Add the following code (the bold text only) to the body of the session bean methods to display the status of the bean instance:

/**

* @see javax.ejb.SessionBean#ejbActivate()

*/

public void ejbActivate() {

System.out.println("ejbActivate() on obj " + this);

}

...

/**

* @see javax.ejb.SessionBean#ejbPassivate()

*/

public void ejbPassivate() {

System.out.println("ejbPassivate() on obj " + this);

}

...

/**

* @see javax.ejb.SessionBean#ejbRemove()

*/

public void ejbRemove() {

System.out.println("ejbRemove() on obj " + this);

}

...

/**

* See section 7.10.3 of the EJB 2.0 specification

*/

public void ejbCreate() {

System.out.println("ejbCreate() on obj " + this);

}

  1. In the IDE, choose File -> Save All.

This will save the GreeterDB session bean and the changes that you have made thus far.



Note

Why select Save All? In many cases, your work is saved automatically by the IDE. However, use File -> Save All whenever you wish to either leave the tutorial for an extended period of time or want to make sure all your work is saved. You may also use the Save and Save All buttons in the toolbar save modifications.



Create a Business Method

The EJB Builder automatically generated the required methods of the session bean and you have customized these methods with output statements. Now you need to add a simple business method to the bean. This method, getGreeting(), generates a greeting based on the current time.

To create the getGreeting() business method:

  1. Right-click the GreeterDB (EJB) node and choose Add Business Method.
  2. The Add New Business Method dialog box appears.

  3. Type getGreeting in the Name field.
  4. Choose java.lang.String in the Return Type field.
  5. The completed dialog window should look like this:


Screen shot showing Add New Business Method dialog box

  1. Click OK.
  2. The getGreeting() business method is added to the GreeterDB session bean and its method signature is automatically added to the GreeterDB bean's remote interface.

  3. Expand the GreeterDB (EJB) node and its Business Methods node.
  4. The getGreeting() method node is displayed under the Business Methods node.


    Screen shot showing GreeterDB(EJB) under ejb,  GreeterDB(EJB),  Business Methods folder of Filesystems window

  1. Double-click the getGreeting() method node.
  2. The source editor displays the content of the bean implementation source file and places the cursor at the start of the getGreeting() method.

  3. Add the following code (the bold text only) to the body of the getGreeting() method:

public java.lang.String getGreeting() {

System.out.println("GreeterDB EJB is determining message...");

String message = null;

Calendar calendar = new GregorianCalendar();

int currentHour = calendar.get(Calendar.HOUR_OF_DAY);

if(currentHour < 12) {

   message = "morning";

} else {

   if((currentHour >= 12) &&

         (calendar.get(Calendar.HOUR_OF_DAY) < 18)) {

      message = "afternoon";

   } else {

      message = "evening";

   }

}

System.out.println("- Message determined successfully");

return message;

}

  1. Add an import statement (the bold text only) for the java.util.* package at the top of the source file.

package samples.jdbc.simple.ejb;

import javax.ejb.*;

import java.util.*;

...

  1. In the source editor window, right-click and select Save to ensure that your changes have been saved.
  2. In the Explorer window, right-click the GreeterDB (EJB) node and select Validate EJB.
  3. An Output Window specifying "Finished GreeterDB (EJB)" should be displayed.

    If this message is not displayed, the code segments above were not copied properly into the source file. Based on the specific error displayed as a result of the validation step, go back and double check your source code.



Note

What happens during Validate? The IDE's EJB Builder contains a custom compiler that not only compiles the EJB source code, but also validates your enterprise beans against the Enterprise JavaBeans[tm] specification.



After the bean validates successfully, close the source code editing window and proceed to Testing the Session Bean to use the IDE's built-in EJB test facility.

Testing the Session Bean

The IDE includes a facility to automatically generate a test environment for the Enterprise JavaBeans[tm]. This feature creates a web-based test client application and packages it along with the enterprise bean. You can use this test application to create an instance of the enterprise bean and to interact with it. In this section you will use this test facility to exercise the GreeterDB bean's create() and getGreeting() methods.

  1. Create the Test Client
  2. Deploy the Test Client
  3. Run the Test Client

Create the Test Client

When you create a test client, the IDE generates an EJB[tm] module, supporting elements, and a J2EE[tm] application module.

To create a test client for the GreeterDB session bean:

  1. Right-click the GreeterDB (EJB) node and select Create New EJB Test Application.
  2. The EJB Test Application wizard is displayed.

  3. Accept all default values and click the OK button.
  4. A progress monitor appears briefly and then goes away when the process is complete.

    Another window is displayed informing you that the web module that was created is also visible in the Project tab. It should go away automatically also. If not, click OK to close the window.

  5. View the resulting test objects in the Explorer.

The IDE has created an EJB module named GreeterDB_EJBModule, a web module named GreeterDB_WebModule, and a J2EE application named GreeterDB_TestApp in the ejb subdirectory.

The EJB module contains the GreeterDB session bean. The web module contains a number of JavaServer Pages[tm] pages and Java class files that make up the test client. The J2EE application includes references to the EJB module and to the web module. In addition, the IDE mounts the web module.


Screen shot of Filesystems window, showing GreeterDB_TestApp highlighted in ejb folder



Note

Confusing list of icons? To avoid confusion amongst the various nodes representing your business application EJB and the automatically generated test application, you have the option during the creation of the test application to specify both the location of the test application and Java package names used in the test application.





Caution

Content of Test Application: The EJB module, web module, and J2EE application generated by the IDE are not intended to be modified. If you modify them you might not be able to redeploy the J2EE test application.



Deploy the Test Client

Before deploying the test application, ensure that the application server is running and it is set as the default server in the IDE.

To deploy the test application:

  1. Right-click the GreeterDB_TestApp J2EE application node and select Deploy.
  2. The progress of the deployment process is displayed in a dialog window.

    See the new tabs in the IDE's Output window that display messages about the deployment.

  3. Click the server1(localhost:port):server.log tab in the output window.
  4. The server.log view displays any error conditions that prevent deployment. When the deployment was successful, the output window resembles the following:


Screen shot of server1(localhost:4848):server.log window showing output messages

  1. On the IDE's toolbar, select the Editing tab.
  2. The Explorer window should be displayed. If not, select View -> Explorer from the IDE's menu bar.

  3. In the Explorer window, select the Runtime tab.
  4. Expand the Server Registry, Installed Servers, Sun ONE Application Server 7, localhost:port, server1(localhost:port), and Deployed Applications nodes.
  5. You should see the GreeterDB_TestApp node under the Deployed Applications node. If the GreeterDB_TestApp node is not listed, right-click on the Deployed Applications node and select Refresh List.



Note

What happens during deployment? The IDE automatically assembles the EAR file and contacts the administrative server of the specified application server to carry out the deployment.

During the initial deployment of an application containing EJBs, the administrative server automatically generates the EJB's stubs and skeletons. Until the EJB interfaces are changed, subsequent redeployment of the application does not entail stub and skeleton generation. This smart redeployment feature greatly optimizes redeployment operations.



Run the Test Client

Since the test client is web-based, you need to open a web browser window to access the initial test page of the generated web application.

On the initial test client's web page, you'll invoke the create() method of the GreeterDB bean's home interface to create an instance of the bean. Then you'll execute the getGreeting() business method of the bean.

To test the GreeterDB bean:

  1. Start a web browser and point it to the following URL:
  2. http://localhost:port/GreeterDB_TestApp

    Where port is the HTTP server port number specified during installation. The default HTTP server port number is 80, but it may be different based on the ports in use during installation.

    Your browser displays the test client.



Caution

Forgot the HTTP Server's Port Number? If you do not remember the HTTP server port number of the application server instance, you can determine the appropriate value by looking at the properties of the application server instance.

1. Under the Runtime tab of Explorer, expand the Server Registry, Installed Servers, Sun ONE Application Server 7, localhost:port

2. Right click the server1(localhost:port) object and select Properties.

3. Read the HTTP server's port number from the Server Instance Port property.




Screen shot of test client in browser window: List of instances being tested; list of objects created during the test session; area where results of last method invocation are shown; and area where you can enter parameters and invoke methods

From this page, you can invoke the methods of the GreeterDBHome remote interface.



Note

Speed of first access: When you visit a JavaServer Pages[tm] (JSP[tm]) page for the first time, the JSP file is compiled into servlet source code and the servlet source code is compiled into a servlet class file. This one time compilation step accounts for the delay in displaying the test client page. After the JSP page has been compiled as part of the first access, subsequent requests are processed very quickly and the resulting page appears almost immediately. Force a reload of the page to see how quickly the subsequent next visit is handled. To force a reload, press the shift key and click the reload button on your web browser.



  1. Click the Invoke button next to the create method to create an instance of the GreeterDB bean.
  2. The create method is under the heading "Invoke Methods on samples.jdbc.simple.ejb.GreeterDBHome."

    The web browser displays the new GreeterDB instance as shown below:


    Browser window for test client showing EJB Navigation area, Stored Objects area, and Results of Last Method Invocation area - method invoked create()

    Notice that the samples.jdbc.simple.ejb.GreeterDB [7] item is added in the instances list in the upper left hand portion of the page. The item represents the instance of the GreeterDB bean created by invoking the create method on the GreeterDBHome interface.

  3. Click the samples.jdbc.simple.ejb.GreeterDB [7] instance link.
  4. This action selects the GreeterDB instance as the EJB module to test. The web browser displays the methods that can be invoked, including the getGreeting() business method.

  5. Click the Invoke button next to the getGreeting method.
  6. The getGreeting() method is called, and its return value is listed in the Results area:


    Test Client browser window showing Results area, method invoked: getGreeting()

    In the example above, the web browser above shows the word "evening" as the return value. Because the getGreeting() method generates a greeting based on the current time, you might see a different greeting value.

  7. In the main menu bar of the IDE, select the Running tab. In the Output window, click the server1:(localhost:port): access tab.
  8. A display of the HTTP requests and responses processed by the application server is shown:


    Screen shot of Output Window server1(localhost:4848):access with output messages

If you encountered problems while running your EJB, you might normally want to exercise the debugging facilities at this stage. However, for the purposes of this tutorial, we'll defer debugging exercises until we develop and deploy the combined web and EJB application.

Now that you've successfully tested your session bean, proceed to Packaging the Enterprise Bean in an EJB[tm] Module to prepare to include the EJB in an enterprise application.

Packaging the Enterprise Bean in an EJB[tm] Module

Although the test client automatically packaged your session bean in an EJB module, this module was specifically created for testing purposes. In this section you will package your session bean in a new EJB module that will be used as part of your enterprise application.

To create the EJB module:

  1. In the Explorer, select the Filesystem tab. (You might need to click the GUI Editing tab of the IDE's menu bar to display the Explorer window).
  2. Right-click the .../mysimple/src filesystem and select New -> J2EE -> EJB Module
  3. Type jdbcSimpleEjb in the Name field.
  4. Click Finish.
  5. Right-click the new jdbcSimpleEjb EJB module and select Add EJB....
  6. The Add EJB to EJB Module browser is displayed.

  7. Select the GreeterDB (EJB) bean under the mysimple/src/samples/jdbc/simple/ejb node
  8. Click OK.

The GreeterDB session bean is included in the EJB module. Expanding the jdbcSimpleEjb node shows the included session bean.


Screen shot of Filesystems window with jdbcSimpleEjb node expanded

Now that you've prepared the EJB for assembly in an enterprise application, proceed to Creating the Web Application to create the web interface portion of the application.

Creating the Web Application

In this section you will develop the web application by creating the servlet, JavaServer Pages[tm] (JSP[tm]) pages and HTML files and packaging them in a web application module.

Create the Web Module

To create a web module:

  1. In the Explorer window, select the the Filesystems node, right click, and select Mount -> Local Directory.
  2. The New Wizard - Local Directory dialog window appears.

  3. Navigate into the mysimple/src directory.
  4. Within the src/ directory, click the Create New Folder button.
  5. A new directory named New Folder is created.

  6. Rename the new directory to jdbcSimpleWeb. To rename the directory, click the New Folder directory icon, pause for a few seconds, and click the directory icon again, type jdbcSimpleWeb, and press the Enter key.
  7. Select the jdbcSimpleWeb directory icon and click Finish. The new directory is mounted in the Explorer window as a filesystem.


Screen shot of Filesystems window showing jbdbSimpleWeb  as a file node

  1. Right-click the mysimple/src/jdbcSimpleWeb filesystem that you just mounted and select New -> JSP & Servlet -> Web Module.
  2. The New wizard appears, showing mysimple/src/jdbcSimpleWeb in the Directory field.

  3. Click Finish.
  4. The Question dialog box appears.

  5. Click OK in the Question dialog box. The IDE creates a web module.
  6. A window might be displayed informing you that the web module is visible in the Project tab. If it appears, click OK to close the window.

  7. Expand the mysimple/src/jdbcSimpleWeb filesystem.
  8. You will see a WEB-INF node under the filesystem.


Screen shot of Filesystems window showing WEB-INF node showing up under the jdbcSimpleWeb file node

Create Servlets

You will now create two servlets that handle requests. The first servlet, named GreeterDBServlet, requests greetings from the GreeterDB session bean, logs the greeting to the database, and delivers the result via a JSP page. The second servlet, named GreeterDBLogDisplayServlet, retrieves previously generated greetings from the database and displays them via another JSP page.

Create GreeterDBServlet

  1. Expand the WEB-INF folder of the web module filesystem, right-click the Classes folder and select New -> Java Package.
  2. The New Wizard appears.

  3. Type samples.jdbc.simple.servlet in the Name field and click Finish.
  4. The new samples.jdbc.simple.servlet package is created under the WEB-INF/Classes folder.

  5. Expand the Classes folder and its nested folders.


Screen shot of Filesystems windows showing WEB-INF node exploded

  1. Right-click the servlet folder and select New -> JSP Servlet -> Servlet.
  2. The New Wizard appears.

  3. Type GreeterDBServlet in the Name field.
  4. Click Finish.
  5. The GreeterDBServlet servlet is created in the servlet package and is displayed in the source editor.

  6. Add the following import statements in bold to the top of the source file below the package statement.
  7. package samples.jdbc.simple.servlet;

    import javax.servlet.*;

    import javax.servlet.http.*;

    import java.io.*;

    import java.util.*;

    import javax.naming.*;

    import javax.ejb.*;

    import java.sql.*;

    import javax.sql.*;

    import samples.jdbc.simple.ejb.*;

    public class GreeterDBServlet extends HttpServlet {

  8. Replace the body of the doGet() method with the following code in bold:
  9. public void doGet (HttpServletRequest request,HttpServletResponse response)

    throws ServletException, IOException {

       javax.ejb.Handle beanHandle;

       GreeterDBHome myGreeterDBHome;

       GreeterDB myGreeterDBRemote;

       InitialContext initContext = null;

       Hashtable env = new java.util.Hashtable(1);

       System.out.println("\nGreeterDBServlet is executing ...");

       System.out.println("Retrieving JNDI initial context...");

       try {

          initContext = new javax.naming.InitialContext();

          System.out.println("- Retrieved initial context successfully");

       }

       catch (Exception e) {

          System.out.println("- Exception creating InitialContext: " + e.toString());

          return;

       }

       try {

          System.out.println("Looking up dbGreeter bean home interface...");

          String JNDIName = "java:comp/env/ejb/jdbc-simple";

          System.out.println("- Looking up: " + JNDIName);

          myGreeterDBHome = (GreeterDBHome)initContext.lookup(JNDIName);

          System.out.println("- Looked up the EJB successfully");

       }

       catch(Exception e) {

          System.out.println("- Greeter bean home not found - " +

          "Is bean registered with JNDI?: " + e.toString());

          return;

       }

       try {

          System.out.println("Creating the dbGreeter bean...");

          myGreeterDBRemote = myGreeterDBHome.create();

          System.out.println("- Created EJB successfully");

       }

       catch(CreateException e) {

          System.out.println("- Could not create the dbGreeter bean: " + e.toString());

          return;

       }

       System.out.println("Getting the message from the dbGreeter bean...");

       String theMessage = myGreeterDBRemote.getGreeting();

       System.out.println("- Got this message from greeter bean: " + theMessage);

       System.out.println("Getting the name input to this servlet...");

       String name = request.getParameter("name");

       System.out.println("- Got name: " + name);

       System.out.println("Recording the greeting in the database...");

       StringBuffer timeStamp = new StringBuffer();

       Calendar rightNow = Calendar.getInstance();

       timeStamp.append(rightNow.get(Calendar.MONTH)+1); timeStamp.append("/");

       timeStamp.append(rightNow.get(Calendar.DAY_OF_MONTH)); timeStamp.append("/");

       timeStamp.append(rightNow.get(Calendar.YEAR)); timeStamp.append(" ");

       timeStamp.append(rightNow.get(Calendar.HOUR_OF_DAY)); timeStamp.append(":");

       timeStamp.append(rightNow.get(Calendar.MINUTE)); timeStamp.append(":");

       timeStamp.append(rightNow.get(Calendar.SECOND)); timeStamp.append(":");

       timeStamp.append(rightNow.get(Calendar.MILLISECOND));

       StringBuffer query = new StringBuffer("insert into Greeting (timeStamp,name,message) values ");

       query.append("('");

       query.append(timeStamp.toString()); query.append("','");

       query.append(name); query.append("','");

       query.append("Good " + theMessage); query.append("')");

       try {

          System.out.println("Getting datasource...");

          String dsName = "java:comp/env/jdbc/jdbc-simple";

          DataSource ds = (javax.sql.DataSource)initContext.lookup(dsName);

          System.out.println("- Got datasource successfully");

          System.out.println("Getting connection...");

          Connection conn = ds.getConnection();

          System.out.println("- Got connection successfully");

          System.out.println("Getting statement...");

          Statement stmt = conn.createStatement();

          System.out.println("- Got statement successfully");

          System.out.println("Executing query...");

          int nRows = stmt.executeUpdate(query.toString());

          System.out.println("- Executed query with result: " + nRows);

          System.out.println("Closing statement...");

          stmt.close();

          System.out.println("- Closed statement successfully");

          System.out.println("Closing connection...");

          conn.close();

          System.out.println("- Closed connection successfully");

       }

       catch (Exception ex) {

          System.out.println("- Could not interact with the database");

          System.out.println("Exception: " + ex.toString());

       }

       System.out.println("Storing the message in request object for the JSP...");

       request.setAttribute("message", theMessage);

       System.out.println("- Stored message successfully");

       System.out.println("Dispatching JSP for output...");

       response.setContentType("text/html");

       RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/GreeterDBView.jsp");

       dispatcher.include(request, response);

       System.out.println("- Dispatched JSP successfully");

       System.out.println("\nGreeterDBServlet is all done\n");

       return;

    }

  10. Replace the body of the doPost() method with the following code in bold:
  11. public void doPost (HttpServletRequest request,HttpServletResponse response)

    throws ServletException, IOException {

       doGet(request,response);

    }

  12. Replace the body of the getServletInfo() method with the following code in bold:
  13. public String getServletInfo() {

       return "Call a session bean from a servlet" +

    " and deliver result via a JSP." +

    " Log greeting to database.";

    }

  14. Remove the init(), destroy(), and processRequest() methods from the source code.
  15. Right-click within the source code window, and select Compile.
  16. When the operation is complete, the word `Finished' appears in the IDE's Output window.

Now, you will create the second servlet.

Create GreeterDBLogDisplayServlet

  1. Using the same procedure as before, create new servlet named GreeterDBLogDisplayServlet under the servlet folder.
  2. Add the following import statements in bold to the top of the source file below the package statement.
  3. package samples.jdbc.simple.servlet;

    import javax.servlet.*;

    import javax.servlet.http.*;

    import java.io.*;

    import java.util.*;

    import javax.naming.*;

    import javax.ejb.*;

    import java.sql.*;

    import javax.sql.*;

    import samples.jdbc.simple.ejb.*;

    public class GreeterDBServlet extends HttpServlet {

  1. Replace the body of the doGet() method with the following code in bold:
  2. public void doGet (HttpServletRequest request,HttpServletResponse response)

    throws ServletException, IOException {

       java.sql.ResultSet rs = null;

       java.sql.Connection conn = null;

       java.sql.Statement stmt = null;

       System.out.println("\nGreeterDBLogDisplayServlet is executing...");

       try {

          System.out.println("Getting initial context...");

          InitialContext ctx = new InitialContext();

          System.out.println("- Got initial context successfully");

          System.out.println("Getting datasource...");

          String dsName = "java:comp/env/jdbc/jdbc-simple";

          DataSource ds = (javax.sql.DataSource)ctx.lookup(dsName);

          System.out.println("- Got datasource successfully");

          System.out.println("Getting connection...");

          conn = ds.getConnection();

          System.out.println("- Got connection successfully");

          System.out.println("Getting statement...");

          stmt = conn.createStatement();

          System.out.println("- Got statement successfully");

          System.out.println("Executing query...");

          StringBuffer query = new StringBuffer("select * from Greeting");

          rs = stmt.executeQuery(query.toString());

          System.out.println("- Executed query successfully");

       }

       catch (Exception ex) {

          System.out.println("- Could not interact with the database");

          System.out.println("- Exception: " + ex.toString());

       }

       System.out.println("Storing the data base resuts in request object for JSP...");

       request.setAttribute("dbResults", rs);

       System.out.println("Results stored successfully");

       System.out.println("Dispatching JSP for output...");

       response.setContentType("text/html");

       RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/GreeterDBLogView.jsp");

       dispatcher.include(request, response);

       System.out.println("- Dispatched JSP successfully");

       try {

          System.out.println("Closing statement...");

          stmt.close();

          System.out.println("- Closed statement successfully");

          System.out.println("Closing connection...");

          conn.close();

          System.out.println("- Closed statement successfully");

       }

       catch (Exception ex) {

          System.out.println("- Could not close the statement and connection");

       }

       System.out.println("\nGreeterDBLogDisplayServlet is all done\n");

       return;

    }

  1. Replace the body of the doPost() method with the following code in bold:
  2. public void doPost (HttpServletRequest request,HttpServletResponse response)

    throws ServletException, IOException {

       doGet(request,response);

    }

  3. Replace the body of the getServletInfo() method with the following code in bold:
  4. public String getServletInfo() {

       return "Retrieve greetings from database and display via a JSP.";

    }

  5. Remove the init(), destroy() and processRequest() methods from the source code.
  6. Right-click the GreeterDBLogDisplayServlet servlet in the Explorer and choose Compile.

Define Servlet Mappings

The next step in preparing the servlets for use is to define the names by which the servlets can be referred to in web requests. Servlet mappings are defined at the web module level.

To define the servlet mappings:

  1. Expand the WEB-INF folder and select the web folder in the Explorer window.
  2. The web folder represents the web.xml file, also known as the deployment descriptor, of the web application.

  3. Right-click the web folder and select Properties.
  4. If the Properties window is not already visible, choose View -> Properties.

  5. Select the Servlet Mappings field and then click the ellipsis (...) button.
  6. The Servlet Mappings property editor appears.

  7. Select the row with GreeterDBServlet in the Servlet Name column and click the Edit... button.
  8. Type /GreeterDBServlet in the URL Pattern field.
  9. Click OK.
  10. Make the same type of change for the GreeterDBLogDisplayServlet by setting the URL Pattern field to /GreeterDBLogDisplayServlet.
  11. The Servlet Mappings property editor should look like this when you are finished modifying the mappings:


Screen shot of Property Editor: Servlet Mappings dialog box showing Servlet Name and URL Pattern fields

  1. Click OK to complete the mappings.

Create HTML and JSP Files

The application consists of a single HTML file and two JSP files. In this step, you will create these files.

To create the HTML page and JSP pages:

  1. Right-click the mysimple/src/jdbcSimpleWeb filesystem and select New -> JSP & Servlet -> HTML File.
  2. The New Wizard appears.

  3. Type index in the Name field



Caution

File extensions are added automatically: Since the IDE automatically adds the appropriate extension to the file name as you create new files such as HTML and JSP files, you should not enter the extension when specifying the name of the page.

If you would like to see the file extensions displayed in the Explorer window, go to the IDE's menu bar, select Tools -> Options. Then select IDE Configuration -> System -> System Settings. Set Show File Extensions to True.



  1. Click Finish.
  2. The index.html file is created and is displayed in the source editor.

  3. Copy the content of the index.html file from the following location and paste it into the source editor, overwriting the existing page.
  4. <appserver_install_dir>/samples/jdbc/simple/src/docroot/index.html

  5. Right-click the mysimple/src/jdbcSimpleWeb filesystem again and select New -> JSP & Servlet -> JSP.
  6. The New Wizard appears.

  7. Type GreeterDBView in the Name field.
  8. Click Finish.
  9. The GreeterDBView.jsp file is created and is displayed in the source editor.

  10. Copy the content of the GreeterDBView.jsp file from the following location and paste it into the source editor, overwriting the existing page.
  11. <appserver_install_dir>/samples/jdbc/simple/src/docroot/GreeterDBView.jsp

  12. Create another JSP file named GreeterDBLogView by following the same steps as above, but using the existing GreeterDBLogView.jsp file as the source.

Define EJB Reference

Before using JNDI to look up EJB references, you need to set up a reference declaration. The reference declaration maps the reference name (used in the lookup statement) to an actual enterprise bean.

To set up a reference declaration to the referenced session bean:

  1. Select the web folder in the Explorer, right-click and select Properties.
  2. Select the References tab of the Properties window.
  3. Select the EJB References field and then click the ellipsis (...) button.
  4. The EJB References property editor appears.

  5. Click Add....
  6. Type ejb/jdbc-simple in the Reference Name field.
  7. For the Referenced EJB Name field, click the Browse button.
  8. The Select an EJB browser is displayed.

  9. Select the GreeterDB (EJB) bean under the mysimple/src/samples/jdbc/simple/ejb folder and click OK.
  10. Notice that the Home Interface and Remote Interface fields are automatically filled when you select the referenced enterprise bean. The Add EJB Reference property editor looks like this:


Add EJB Reference dialog box,  Standard tab

  1. Click the Sun ONE App Server tab.
  2. Enter ejb/my-jdbc-simple in the JNDI Name field.



Caution

Avoiding name conflicts: If you already deployed the JDBC Simple application while following the application server's Getting Started guide, the JNDI name ejb/jdbc-simple will have already been registered in the application server environment. Therefore, it is very important that you specify a slightly modified JNDI name, ejb/my-jdbc-simple, for this variant of the JDBC Simple application. Otherwise, JNDI naming conflicts would occur when the application is deployed.



  1. Click OK to close the Add EJB References dialog box.
  2. Click OK to close the EJB References property editor.

Define JDBC Resource Reference

Similar to EJB references, before an application references JDBC resources, these resources must be defined in the module's deployment descriptor.

To add the reference:

  1. In the References tab of the web folder's property window, select the Resource References field and then click the ellipsis (...) button.
  2. The Resource References property editor appears.

  3. Click Add...
  4. Type jdbc/jdbc-simple in the Name field.
  5. This reference name must match the JNDI name used in the servlets.

  6. Click the Sun ONE App Server tab.
  7. Type jdbc/jdbc-simple in the JNDI Name field.
  8. This name specifies JDBC resource, defined in the application server's configuration. Later in this tutorial, you will define this resource.


Screen shot of Add Resource Reference window, Standard tab, with Type set to javax.sqlDataSource

  1. Click OK to close the Add Resource Reference dialog box.
  2. Click OK to close the Resource References property editor.

Your next step is to combine the EJB and web modules into an enterprise application. Proceed to Assembling the J2EE[tm] Application.

Assembling the J2EE[tm] Application

You have created the EJB[tm] module and web module so far. You will now create a J2EE application that will be deployed to the application server.

To create the J2EE Application:

  1. Right-click the mysimple/src filesystem select New -> J2EE -> Application.
  2. The New Wizard is displayed.

  3. Type jdbcSimpleApp in the Name field.
  4. Click Finish.
  5. Right-click the jdbcSimpleApp J2EE application node and select Add Module....
  6. The Add Module to Application browser is displayed.

  7. Using the Control key, select both the jdbcSimpleEjb node under the mysimple/src filesystem and the WEB-INF node under the mysimple/src/jdbcSimpleWeb filesystem.


Screen shot of Add Module to Application window,  showing jdbcSimpleEjb and WEB-INF selected in the Select the Module(s) to add to this Application dialog

  1. Click OK.
  2. If you expand the jdbcSimpleApp application node, the two modules are listed:


Filesystem window showing jdbcSimpleWeb and jdbcSimpleEjb under the jdbcSimpleApp node

  1. In the IDE's menu bar, select File -> Save All.

Before exercising the application, you need to configure the database connectivity for the application. Proceed to Setting Up Database Connectivity.

Setting Up Database Connectivity

Since the enterprise application uses the Java Database Connectivity (JDBC[tm]) API to record greetings to a database, you need to define the necessary JDBC-related settings in the application server environment prior to deploying and exercising the application. JDBC configuration involves setting up a JDBC driver, defining a JDBC connection pool and registering the JDBC resources used by your application.

Once you define the necessary JDBC connection pool and resource entries, you will start the PointBase Server database.

Configure the JDBC Driver

A JDBC driver must be configured in the classpath of the application server before you can exercise applications that use JDBC.

Since the PointBase Type 4 JDBC driver should already be configured in your application server instance's environment (based on either the combined installation of the application server with PointBase or through your installation and configuration of PointBase), there is no need for you to perform any additional JDBC driver set up steps.



Caution

Solaris 9 Users: If the application server was installed as part of a Solaris 9 installation, you should have already followed Getting Started with Sun ONE Application Server 7 on the Sun Microsystems documentation web site. While performing the steps in the Getting Started guide, you should have installed PointBase and configured the application server to use the PointBase JDBC driver. If you have not already done so, make sure that you've completed the Getting Started guide prior to continuing with this tutorial.



Define the JDBC Connection Pool

Before running the sample application, you need to define a suitable JDBC connection pool that maps to the PointBase database server and a JDBC resource that associates the JDBC references made in the sample application to the JDBC connection pool definition.

If you already exercised this sample application as part of the Getting Started guide, the JDBC connection pool may already be defined with the application server.

To determine whether or not the connection pool has already been registered:

  1. Select the Runtime tab of the Explorer window.
  2. Expand the Server Registry, Installed Servers, Sun ONE Application Server 7 nodes.
  3. Expand the localhost:4848 node followed by the server1(localhost:port) node. Use the appropriate administrative server port number for your environment.
  4. Attempt to expand the Registered JDBC Connection Pool node to list any registered connection pools.

If you either cannot expand the connection pool node or do not see a connection pool entry named PointBasePool, continue with the next section to register the appropriate connection pool.

If you see an entry named PointBasePool, scan the following instructions to ensure that the settings of this pool match the requirements of the application.

To register the JDBC connection pool:

  1. Right-click the Unregistered JDBC Connection Pools node and select Add New JDBC Connection Pool.
  2. The Properties of JdbcConnectionPool property sheet is displayed.

  3. Type com.pointbase.jdbc.jdbcDataSource in the Datasource Classname.
  4. Type PointBasePool in the Name field.
  5. Select the Properties field and then click the ellipsis (...) button.
  6. A property editor appears without any entries.

  7. Add the following sets of values to the property name, value, and description fields, using the Add button:

Name

Value

DatabaseName

 

jdbc:pointbase:server://localhost/sun-appserv-samples

 

User

 

jdbc

 

Password

 

jdbc

 



Caution

Non-default PointBase Server Port: If you made your own copy of the PointBase Server environment and selected a PointBase server port number other than the default value of 9092, then you need to specify the port number in the DatabaseName property.

The DatabaseName property specified for the JDBC Connection Pool must be changed from:

jdbc:pointbase:server://localhost/sun-appserv-samples

to:

jdbc:pointbase:server://localhost:<port>/sun-appserv-samples

Where <port> is the port number specified in the StartServer script for PointBase.



  1. Click OK.
  2. Clear the value of the Table Name field.


Property Editor:Properties dialog box for Property Name, Property Value, and Description fields

  1. Close the property sheet.
  2. Right-click the PointBasePool node and choose Register.
  3. A new Select Server to Register dialog box appears.

  4. Select server1 and click Register.
  5. An Information dialog box appears indicating a successful registration.

  6. Click OK to close the Information dialog box.
  7. Click OK to close the Select Server to Register to dialog box.
  8. Expand the Registered JDBC Connection Pools node under the server1(localhost:4848) node.
  9. The registered PointBasePool JDBC connection pool is displayed.


Runtime window showing PointBasePool under Registered JDBC Connection Pools node

If you do not see the PointBasePool node under the Registered JDBC Connection Pools node, right-click the Registered JDBC Connection Pools node and select Refresh List.

Define the JDBC Resource

Now that the JDBC connection pool definition has been created, you are ready to define a JDBC resource and associate it with the connection pool entry.

If you already exercised this sample application as part of the Getting Started with Sun ONE Application Server 7 on the Sun Microsystems documentation web site, a suitable JDBC resource may already be defined with the application server.

To determine whether or not a suitable JDBC resource has already been registered:

  1. Expand the localhost:4848 node followed by the server1(localhost:port) node. Use the appropriate administrative server port number for your environment.
  2. Attempt to expand the Registered JDBC DataSources node to list the registered JDBC resources.
  3. If you either cannot expand the JDBC DataSources node or do not see a datasource entry named jdbc/jdbc-simple, continue with the next section to register the appropriate resource.

    If you see an entry named jdbc/jdbc-simple, scan the following instructions to ensure that the settings of this resource match the requirements of the application.

To register the JDBC resource (referred to as a JDBC "DataSource" in the IDE):

  1. Right-click the Unregistered JDBC DataSources node and select Add new Data Source.
  2. The Properties of DataSource property sheet is displayed, and a new DataSource node is created under the Unregistered Data Sources node

  3. Type jdbc/jdbc-simple in the JNDI Name field.
  4. The resource name here must match the JNDI name that you have assigned when creating the web application.

  5. Select PointBase(server1:localhost:port) in the Pool Name field.


Screen shot of Properties sheet, with PointBasePool highlighted for Pool Name field

  1. Close the property sheet.
  2. Right-click the new jdbc-simple node and choose Register...
  3. A Select Server to Register to dialog box is displayed.

  4. Select server1 and click Register.
  5. An Information dialog box appears indicating a success.

  6. Click OK to close the Information dialog box.

  1. Click OK to close the Select Server to Register to dialog box.
  2. Expand the Registered JDBC DataSources node under the server1 (localhost:4848) node.
  3. The registered jdbc/jdbc-simple data source is displayed.


Runtime window with jdbc/jdbc-simple highlighted under the Registered JDBC DataSources node

Start the PointBase Server Database

The database server can be started by performing one of the following actions:

  • Windows Platforms:
  • PointBase installed with the application server:

    Start -> Programs -> Sun Microsystems -> Sun ONE Application Server 7 -> Start PointBase

    PointBase downloaded and installed separately:

    Execute: <pointbase_install_dir>/tools/server/startserver.bat

  • UNIX Platforms:
  • PointBase installed with the application server:

    Execute: <appserver_install_dir>/pointbase/server/StartServer.sh

    PointBase downloaded and installed separately:

    Execute: <pointbase_install_dir>/tools/server/startserver.sh

Once you execute this script, you will see the following text in either a command window or at the UNIX terminal prompt:

Server started, listening on port 9092, display level: 0 ...
>

You are finally ready to exercise the application. Proceed to Deploying and Running the J2EE[tm] Application.

Deploying and Running the J2EE[tm] Application

In this exercise you will first override the default value assigned to the context root of the web application. Then you will deploy and run the application.

Disable EJB Test Application

Since both the EJB Test and the JDBC Simple applications contain the same EJB module, if you attempted to deploy the JDBC Simple application without at least disabling the EJB Test application, a JNDI naming conflict would occur during deployment of the JDBC Simple application. This is because the <jndi-name> value of ejb/my-jdbc-simple as contained in the EJB module's deployment descriptor is scoped globally throughout the application server instance.

To disable the EJB Test application:

  1. In the Explorer, select the Runtime tab and drill down to the server1(localhost:4848) node.
  2. Expand the Deployed Applications node, select GreeterDB_TestApp, right-click and select Disable.

No JNDI naming conflicts will occur with a prior deployment of the JDBC Simple sample application because you changed the JNDI name of the EJB in the second version of this application to a unique value.

Define Web Context Root

The context root provides a way to distinguish resources of one web application from resources of other web applications deployed to the same server instance. You set the context root on the web module object that is represented in the J2EE application object. In this exercise, you will specify my-jdbc-simple as the context root. (If you set the context root to the same value as used by a previously deployed copy of the JDBC Simple sample, an error would occur during deployment because you cannot deploy two web applications with the same context root to the same virtual server).

The context root value determines how end users will access the web application:

http://hostname:port/my-jdbc-simple/...

To define the context root of the web module:

  1. In the Explorer window, under the Filesystems tab, expand the jdbcSimpleApp node, select the jdbcSimpleWeb object, right-click and select Properties.


Filesystems sheet show jdbcSimpleWeb highlighted under the jdbcSimpleApp node

Note that we modify the context setting at the J2EE application level because a single module may be added to different J2EE applications. Each application may require different web context values even though the underlying web application is the same.

  1. Type my-jdbc-simple in the Web Context field.
  2. The property sheet looks like this:


Screen shot of Properties sheet of jdbcSimpleWeb

Deploy the Application

To deploy the application, right-click the jdbcSimpleApp node and select Deploy.

Several views appear in the Output window while a Progress Monitor window shows the deployment progress. Wait for the Progress Monitor to close automatically.

You can monitor the status of the many operations in the IDE through the status area of the IDE's menu bar. As you deploy the application, you will see status information in this area.


Screen shot of Running tab of menu bar showing status information

Run the Application

Before running the application, make sure that the PointBase server is running.

To run the application:

  1. Open a web browser window and access the following URL:
  2. http://hostname:port/my-jdbc-simple/index.html

    When the web browser connects to the server, the server1: access view tab in the output window displays a new line.


Output Window showing server(localhost4848):access tab messages

  1. Enter a name and click Process in the web browser.
  2. As the servlet, EJB, and JSP page are executed, the output of System.out.println statements are displayed in the server1: server.log view tab in the output window.


Output Window showing messages in server.log

  1. Click the here link to display a list of the greeting messages generated thus far.
  2. More log entries appear in the server.log view window.

After having run the application successfully, proceed to Modifying the Application to gain a sense of the speed of typical development activities.

Modifying the Application

In this section, you will leverage the dynamic redeployment feature of the application server by modifying several different components in the application, redeploying and retesting the application without restarting the application server. Each exercise is very basic in that you will modify the source code of various types of files, recompile when necessary and simply redeploy the application. The combination of the IDE's automatic reassembly features and the application server's dynamic redeployment capabilities should make your cycle times as short as possible.

Modify HTML File

  1. In Explorer, double click the index.html file located under the web module.
  2. Change the following line from:
  3. <title>JDBC-SIMPLE Sample Application</title>

    to:

    <title>MODIFIED JDBC-SIMPLE Sample Application</title>

    Also modify the page title that is displayed as part of the HTML content. Change:

    <b><font face="Arial"><font color="#000000"><font size=+2>JDBC-SIMPLE
    Sample Application</font></font></font></b>

    to:

    <b><font face="Arial"><font color="#000000"><font size=+2>MODIFIED JDBC-SIMPLE
    Sample Application</font></font></font></b>

  4. Save your changes to the file.
  5. Select the jdbcSimpleApp node in Explorer, right-click and select Deploy.
  6. After deployment completes, access the application to see the change.
  7. You should see the modified page title at the top of the browser window.

Modify JavaServer Pages[tm] (JSP[tm]) File

  1. In Explorer, double click the GreeterDBView.jsp file located under the web module.
  2. Change the following line from:
  3. Good <%= messageString%>, <%= nameString%>. Enjoy your <%= messageString%>.

    to:

    Good <%= messageString%>, <%= nameString%>. Have a great <%= messageString%>.

  4. Save your changes to the file.
  5. Select the jdbcSimpleApp node in Explorer, right-click and select Deploy.
  6. After deployment completes, access the application to see the change.
  7. Enter your name and click Process.

    You should see the modified greeting string.

  8. Access the application once more to see how quickly the subsequent requests are processed.

Modify Servlet

  1. In Explorer, navigate to the GreeterDBServlet file under the WEB-INF -> Classes area of the mounted web module.
  2. Double click the GreeterDBServlet located under the web module.
  3. In the doGet() method, change the following line from:
  4. System.out.println("\nGreeterDBServlet is executing...");

    to:

    System.out.println("\nMODIFIED GreeterDBServlet is executing...");

  5. Recompile the servlet by right clicking on the source editor and selecting Compile.
  6. Select the jdbcSimpleApp node in Explorer, right-click and select Deploy.
  7. After deployment completes, run the application and monitor the server log file. Look for the MODIFIED string to appear at the very beginning of the stdout messages generated by the application.

Modify EJB

  1. In Explorer, navigate to the GreeterDBBean file under the mysimple/src filesystem.
  2. Double click the GreeterDBBean object.
  3. In the getGreeting() method, change the following line from:
  4. System.out.println("GreeterDB EJB is determining message ...");

    to:

    System.out.println("MODIFIED GreeterDB EJB is determining message ...");

  1. Recompile the implementation class by right clicking on the source editor and selecting Compile.
  2. Select the jdbcSimpleApp node in Explorer, right-click and select Deploy.
  3. After deployment completes, run the application and monitor the server log file. Look for the MODIFIED string to appear in the stdout messages generated by the application.

Now that you've experienced the quick modification cycle, proceed to Debugging the Application to gain a sense of stepping through various components of the application.

Debugging the Application

This section introduces you the ease by which you can debug class files and JavaServer Pages[tm] (JSP[tm]) source files using the IDE and the application server. To start debugging with the application server there is no set up required outside the IDE. All underlying debugging configuration is established automatically by the IDE and the application server.

Prepare Web Module for Debugging

Verify that several web module settings are defined for debugging JSP files. Also set the context root value in the web module.

  1. In Explorer, navigate to the mysimple/src/jdbcSimpleWeb filesystem.
  2. Select the web module's web.xml node and display its property sheet.
  3. Select Sun ONE AS tab.
  4. Select the JSP Param field and then click the ellipsis (...) button.
  5. Verify that classdebuginfo and mappedfile properties are set to true.
  6. Click OK to close the property editor.
  7. Select the web module's WEB-INF node in the mysimple/src/jdbcSimpleWeb filesystem and display its property sheet.
  8. Enter /my-jdbc-simple in the Context Root field.
  9. This value matches the servlet context root value that you assigned while defining the web application.

Start the Debugger

To start the debugger:

  1. Choose the jdbcSimpleApp J2EE application node.
  2. In the IDE's main menu bar, choose Debug -> Start.

The server1 instance of the application server restarts, and the IDE switches to the debugging workspace. In addition, the index.html page is displayed in the web browser. Note that the application is redpeloyed before the debugging session begins.



Caution

Browser does not come up? Depending on the browser in use, you might have to access the web application through your browser directly.



Debug the EJB

  1. Open GreeterDBBean.java file in the source editor.
  2. Move the cursor to the following line:
  3. if(currentHour < 12) {

  4. Right-click and select Debug -> Toggle Breakpoint.
  5. The line in the source editor changes its background color indicating that a breakpoint has been set.

  6. In the web browser, type a name, for example TESTER, and click Process.
  7. Execution of GreeterDBBean.java stops at the breakpoint, and the line is highlighted in another color.

  8. In the IDE's main menu bar, select the Debug tab.
  9. In the Call Stack view, expand the samples.jdbc.simple.ejb.GreeterDBBean.getGreeting node.

    Under the node, you can see the variables declared in the getGreeting method. One of the variables is named currentHour and it stores the current hour.

  10. In the IDE's main menu bar, choose Debug -> Step Over a few times until the execution reaches the System.out.println statement.
  11. The value of the message variable changes from null to "morning," "afternoon," or "evening" depending on the value of currentHour variable.

  12. Select the message variable and display its properties.
  13. If the properties sheet is not visible, click Properties () button in the Debug window.

  14. Type "day" (including the quotes) in the Value field.
  15. Select Debug -> Continue.
  16. The debugger continues execution, and the web browser greets "Good day, TESTER."

  17. Move the cursor to the line with the breakpoint and select Debug -> Toggle Breakpoint.
  18. The breakpoint is removed from the line, and its background color resets to the normal editing color.

Debug a JSP

To debug GreeterDBView.jsp:

  1. Open GreeterDBView.jsp in the source editor.
  2. Move the cursor to the following line:
  3. Good <%= messageString%>, <%= nameString%>.

  4. Right-click inside the source editor and choose Compile.
  5. You must compile the JSP in the IDE to allow the IDE to correlate between the JSP source file statements and the underlying servlet class file which implements the JSP file.

  6. Right-click and select Debug -> Toggle Breakpoint.
  7. The line in the source editor changes its background color indicating that breakpoint has been set.

  8. In the web browser, type a name, for example TESTER, and click Process.
  9. Execution of the GreeterDBView.jsp page stops at the breakpoint, and the line is highlighted indicating that execution stopped at the line.

  10. In the Call Stack view, expand the _jasper._GreeterDBViwe_jsp._jspService node.
  11. Under the node, you can see the variables for GreeterDBView.jsp.

  12. Select nameString variable.
  13. Next to the nameString variable, the "TESTER" string is shown because the name, entered in Step 5, is stored in the nameString variable.

  14. Type "HUMAN" (including the quotes) in the Value field.
  15. The value of nameString variable changes to "HUMAN".

  16. In the IDE's main menu bar, select Debug -> Continue.
  17. The debugger now continues execution of GreeterDBView.jsp, and the web browser shows HUMAN in the greeting instead of TESTER.

  18. Move the cursor to the line with the breakpoint and select Debug -> Toggle Breakpoint.
  19. The breakpoint is removed from the line, and its background color resets to the normal editing color.

Stop the Debugger

To stop the debugger:

  1. In the IDE's main menu bar, select Debug -> Finish.
  2. The Finish Debugging Session dialog box appears.

  3. Make sure that all running sessions are checked.
  4. Click OK.

Once you have completed these exercises, proceed to the final section, Summary.


Previous      Contents      Index      Next     
Copyright 2002 Sun Microsystems, Inc. All rights reserved.