Sun Microsystems Logo

 

 
 

Sun[tm] ONE Studio 4, Enterprise Edition for Java[tm] with Application Server 7 Tutorial
Creating the Web Application
PREV PREV NEXT

 

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.

  1. Create the Web Module
  2. Create Servlets
  3. Define Servlet Mappings
  4. Create HTML and JSP Files
  5. Define EJB[tm] Reference
  6. Define JDBC[tm] Resource Reference


1. 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.

The New Wizard - Local Directory dialog window appears.

2. Navigate into the mysimple/src directory.

3. Within the src/ directory, click the Create New Folder button.

A new directory named New Folder is created.

4. 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.

5. Select the jdbcSimpleWeb directory icon and click Finish. The new directory is mounted in the Explorer window as a filesystem.

6. Right-click the mysimple/src/jdbcSimpleWeb filesystem that you just mounted and select New -> JSP & Servlet -> Web Module.

The New wizard appears, showing mysimple/src/jdbcSimpleWeb in the Directory field.

7. Click Finish.

The Question dialog box appears.

8. Click OK in the Question dialog box. The IDE creates a web module.

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.

9. Expand the mysimple/src/jdbcSimpleWeb filesystem.

You will see a WEB-INF node under the filesystem.


2. 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.

The New Wizard appears.

2. Type samples.jdbc.simple.servlet in the Name field and click Finish.

The new samples.jdbc.simple.servlet package is created under the WEB-INF/Classes folder.

3. Expand the Classes folder and its nested folders.

4.Right-click the servlet folder and select New -> JSP Servlet -> Servlet.

The New Wizard appears.

5. Type GreeterDBServlet in the Name field.

6. Click Finish.

The GreeterDBServlet servlet is created in the servlet package and is displayed in the source editor.

7. Add the following import statements in bold to the top of the source file below the package statement.

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:

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;  
  }  

9. Replace the body of the doPost() method with the following code in bold:

public void doPost (HttpServletRequest request,HttpServletResponse response) 
   throws ServletException, IOException { 
    doGet(request,response); 
}

10. Replace the body of the getServletInfo() method with the following code in bold:

public String getServletInfo() { 
    return "Call a session bean from a servlet" +
           " and deliver result via a JSP." +
           " Log greeting to database."; 
} 

11. Remove the init(), destroy(), and processRequest() methods from the source code.

12. Right-click within the source code window, and select Compile.

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.

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 {

3. Replace the body of the doGet() method with the following code in bold:

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;  
  }  

4. Replace the body of the doPost() method with the following code in bold:

public void doPost (HttpServletRequest request,HttpServletResponse response) 
   throws ServletException, IOException { 
    doGet(request,response); 
} 

5. Replace the body of the getServletInfo() method with the following code in bold:

public String getServletInfo() { 
    return "Retrieve greetings from database and display via a JSP."; 
}

6. Remove the init(), destroy() and processRequest() methods from the source code.

7. Right-click the GreeterDBLogDisplayServlet servlet in the Explorer and choose Compile.

3. 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.

The web folder represents the web.xml file, also known as the deployment descriptor, of the web application.

2. Right-click the web folder and select Properties.

If the Properties window is not already visible, choose View -> Properties.

3. Select the Servlet Mappings field and then click the ellipsis (...) button.

The Servlet Mappings property editor appears.

4. Select the row with GreeterDBServlet in the Servlet Name column and click the Edit... button.

5. Type /GreeterDBServlet in the URL Pattern field.

6. Click OK.

7. Make the same type of change for the GreeterDBLogDisplayServlet by setting the URL Patter field to /GreeterDBLogDisplayServlet.

The Servlet Mappings property editor should look like this when you are finished modifying the mappings:

8. Click OK to complete the mappings.

4. 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.

The New Wizard appears.

2. Type index in the Name field.

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.

3. Click Finish.

The index.html file is created and is displayed in the source editor.

4. Copy the content of the index.html file from the following location and paste it into the source editor, overwriting the existing page.

<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.

The New Wizard appears.

6. Type GreeterDBView in the Name field.

7. Click Finish.

The GreeterDBView.jsp file is created and is displayed in the source editor.

8. Copy the content of the GreeterDBView.jsp file from the following location and paste it into the source editor, overwriting the existing page.

<appserver_install_dir>/samples/jdbc/simple/src/docroot/GreeterDBView.jsp

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

5. 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.

The EJB References property editor appears.

4. Click Add....

5. Type ejb/jdbc-simple in the Reference Name field.

6. For the Referenced EJB Name field, click the Browse button.

The Select an EJB browser is displayed.

7. Select the GreeterDB (EJB) bean under the mysimple/src/samples/jdbc/simple/ejb folder and click OK.

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:

8. Click the Sun ONE App Server tab.

9. Enter ejb/my-jdbc-simple in the JNDI Name field.

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.

9. Click OK to close the Add EJB References dialog box.

10. Click OK to close the EJB References property editor.

6. 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.

The Resource References property editor appears.

2. Click Add...

3. Type jdbc/jdbc-simple in the Name field.

This reference name must match the JNDI name used in the servlets.

4. Click the Sun ONE App Server tab.

5. Type jdbc/jdbc-simple in the JNDI Name field.

This name specifies JDBC resource, defined in the application server's configuration. Later in this tutorial, you will define this resource.

6. Click OK to close the Add Resource Reference dialog box.

7. 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 Application.

PREV PREV NEXT