Previous Next Contents Index


Creating Presentation Logic

This section describes the concepts and tasks associated with creating the presentation logic for web applications and describes how to use Netscape Application Builder's Java editor and Properties window to customize servlets..

The following topics are described in this section:


About Java Servlets
A Java servlet contains the application code that executes on the server in response to an event. A servlet receives events from the web application page, performs the appropriate actions, and then subsequently outputs data dynamically to the application's presentation layout model by invoking a JavaServer Page (JSP).

Servlets have the following characteristics:

A servlet does not necessarily have to be designed for one specific application; you could create a library of servlets to be used across multiple applications. There are advantages to writing application-specific servlets, however, especially in terms of application configuration issues.

For a more in-depth description of how to design and create servlets programmatically, see Controlling Applications with Servlets.

How Servlets Control the Presentation Logic
The design of the application's presentation, data access, and business logic help to determine the design of each servlet. In addition, the number and type of the servlets required to control the presentation logic can be designed from the point of view of the possible interactions a user may input while using the application.

A user's interaction with an application takes place via JavaServer Pages (JSPs). Information entered on a page form is sent to the servlet in a request object and is processed by the servlet's service() method. The servlet then sets up a response by performing any necessary business logic functions, such as accessing databases or directories or performing complex calculations on provided data. Business logic is usually performed by external objects, such as Enterprise JavaBeans (EJBs) and not by the servlet itself. For more information about EJBs, seeCreating Business Logic.

The servlet-generated response is an HTML page or a JSP that contains information associated with the request, which sets up the next interaction. This page can be immediately returned and displayed by the client object, or generated by invoking a JavaServer Page (JSP) which assembles the response and passes it back to the client browser.

Servlets Work with Various Types of Components
To control the application's presentation logic, servlets need to communicate with various types of additional project components. These servlet-related components include the following types of project files or APIs:

Servlet Configuration (NTV) Files
Servlet configuration information is stored in a property file using a name-type-value (NTV) format. You can use one NTV file to control one or more servlets.

For more information about NTV files, see Servlet Configuration.

JDBC RowSet Interface
A JDBC RowSet object is a Java object that encapsulates a set of rows that have been retrieved from a database or other tabular data source, such as a spreadsheet. The RowSet interface provides JavaBean properties that allow a RowSet instance to be configured to connect to a data source and retrieve a set of rows.

For more information about the JDBC RowSet interface, see Creating Data Access Logic.

Session Management Mechanisms
A session represents a series of user-application interactions that are tracked by the server application. Tracking sessions enables an application to maintain a separate context for each user, and to provide security for such interactions (for example, a validated user login followed by a series of directed activities for that particular user).

Netscape Application Builder enables you to track session information via the following mechanisms:

For more information about session management and designing servlets that process session data via a session-tracking mechanism, see Working with Session Management.

Enterprise JavaBeans
Servlets act as the central dispatcher for your application and handle presentation logic; Enterprise JavaBeans (EJBs) do the bulk of your application's actual data and business rules processing. However, note that EJBs provide no presentation (actual page flow or layout, or the logic behind such) or visible user-interface services. Each EJB encapsulates one or more application tasks or application objects. Typically, they take parameters and send back return values.

For more information about Enterprise JavaBeans, seeCreating Business Logic.

JavaServer Pages
A JavaServer Page (JSP) is an HTML file, with Sun-specified extensions, that is executed on a web server or application server instead of on a client, dynamically creating pure HTML, which is then sent to the client. The JSP has some new tags—extensions found only in JSP. These keywords allow the author to embed scripts and expressions in any scripting language (the default is Java); perform NCSA-standard server-side includes (incorporating other JSPs from the server) conditionally or unconditionally, call Java Servlets, and call Enterprise Java Beans (EJBs) to perform tasks on the server, and generate output to be incorporated into the dynamic HTML stream.

For more information about JavaServer Page, seeCreating Presentation Layout.


Standard Servlets
You can choose to only create standard servlets and use Netscape Application Builder to connect these servlets to JSPs. If you use standard servlets exclusively, you gain portability for your application; however, you lose the benefits of the extensions provided by Netscape Application Builder, which are described in the following section, "What the NAS Extended Runtime Servlet Model Provides" on page 311.

To create only standard servlets:

  1. Choose Development options from the Tools menu.
  2. Choose the Code Generation tab.
  3. Uncheck the "Use Extended NAS API for Generic Servlet?" option.
  4. Click OK.
This selection causes the New Servlet wizard to create servlet classes that extend HttpServlet and implement an empty service() method.

Note. Other Netscape Application Builder wizards that create servlets only use the NAS extended API, which is not standard.


What the NAS Extended Runtime Servlet Model Provides
In addition to supporting the standard Java servlet model, Netscape Application Builder provides the following servlet runtime features:

For more information about NAS extended services, see the Programmer's Guide.

Servlets: A Code Walkthrough Example
A servlet acts much like a "controller" in the MVC (Model/View/Controller) user interface architecture. A servlet receives user-generated events and directs changes to both the underlying "data storage" model, such as Enterprise JavaBeans, the Netscape Application Server session information, and so on, and to the view you want to display, which is either an HTML page or a JavaServer page.

These user-generated events most often come from an HTML form. The server packages the arguments into the request object, and calls the servlet's main entry point. Netscape Application Builder implements this entry-point in your project's BaseServlet file and performs the following actions:


Creating and Editing Servlets
Netscape Application Builder provides a servlet wizard which generates a breed of servlets with added value that enable point and click data binding of servlet data with various types of components in JavaServer Pages (JSPs).

Use the various code generation wizards provided with Netscape Application Builder to generate servlet code automatically. The wizards provide a framework that gives you a head start on the most commonly used types of servlets.

Note. Consider using a Java IDE for coding your presentation logic in Java rather than using the built-in Java code editor, which is best suited for editing minor changes in the application code.

This section describes the following servlet-creation topics:

Creating Servlets via the Add File(s) Dialog Box
To create your Netscape Application Server servlets using wizards, perform the following steps:

  1. Run the appropriate new servlet wizard.
  2. Edit the Netscape Application Builder-generated code.
  3. Compile the servlets.
  4. Test the servlets.
  5. Debug the servlets.
For information about compiling, testing, or debugging servlets, see Compiling, Testing, and Debugging Applications.

You can create new servlets or add additional code to an existing servlet by using wizards, or by editing the files directly. Netscape Application Builder automatically generates Java code based on your selections or insertions.

Editing Servlets
This section describes the specific aspects of a servlet that you can edit using the various Netscape Application Builder tools.

The following table maps the specific servlet components you can edit to the associated Netscape Application Builder servlet editor tool.

Servlet Component
NAB Editor Tool
Parameters
Property window (Outline View)
FormActionHandler
Property window; via the "Events" tab
Business Logic
Pure coding via the Java editor
Output (incl. NTV files)
NTV editor, property window, and Outline View
Caching
Properties window

The Properties editor for a servlet specifies properties that are set when you create the servlet a wizard. You can change the initial parameters, caching information, validation parameters, required sessions, default template, and output result sets. For more information about these properties, see the Programmer's Guide.


Creating FormActionHandlers to Process Requests
Every button on every HTML form can be associated with a servlet "entry-point." An event occurs when a button is activated. The event is directed to a servlet entry point by a FormActionHandlers.

To create a FormActionHandler, perform the following steps:

  1. Open the servlet.
  2. Choose the Properties window and click the Events tab.
  3. Choose Add and enter the input-action name and the method to call when the action occurs.
You can also use the events panel of the Property editor to delete a FormActionHandler, edit the input-action or method name, or locate the source code of an input-action response method in the servlet using the Del, Edit, or Go to buttons in the Event tab, respectively.


Importing Servlets
To import a servlet, perform the following steps:

  1. Copy the servlet file to a directory under the NAS root.
  2. Select Import Servlet(s) from the Project menu.
  3. Select the servlet file, either by navigating or by entering the file name, and click Add.
Netscape Application Builder places the servlets in the correct location in the project tree, depending on whether the servlet is source or compiled code. If an associated NTV file exists for the servlet, it is also imported into the project. The NTV file must be in an ntv subdirectory of the directory that contains the servlet. If an NTV file does not exist in the appropriate location, Netscape Application Builder creates an empty one for you.

Registering, Compiling, and Testing Servlets
Once you have created your Java objects, you can use Netscape Application Builder to register, compile and test them. When you test a Java object, your preferred HTML browser displays an HTML page from which you can submit a request to run the object.

For more information about how to register, compile, and test servlets, see Compiling, Testing, and Debugging Applications.


Working with BaseServlet Files
Your application's initial base class servlet and application resource files are created for you when you first create a new project via the Netscape Application Builder code generation wizards and property editors. A base class servlet (baseServlet.java) is the class from which all other servlet classes for your project are derived; a base session resource (AppResource.java) is the class defined to handle the Netscape Application Server application session variables.

This section describes the concepts and tasks associated with using a base class servlet. For more information about the base session resource file, see Working with Session Management.

Using a Base Servlet Class
A base servlet class enables you to reduce redundant coding by centralizing application functionality and letting other servlets inherit from it.

The base servlet file stores shared code such as classes and methods created by a Netscape Application Builder user. You may want to specify several different Java files to serve as Base servlets in your project if, for example, multiple members of a team are simultaneously working on a Netscape Application Builder project.

Many of the servlet classes in a given application perform similar routine tasks. You might find it helpful to create a base class which contains helper methods to perform the routine tasks that are specific to your application and then derive the other servlets in your application from your base class.

The following list shows a few of the tasks you might perform in the application's servlet base class:

For information which describes how to specify which file is the default base servlet for your project, see Setting Netscape Application Builder Options.

In this manner, common functionality such as error handling and/or new RowSet classes for sets of related servlets can be placed in the base servlet classes or the project-level BaseServlet class.


Working with Session Management
A session is a continuous series of interactions between a user and a Netscape Application Server application. The term session is widely used to refer to a web browser session, but in this manual, the term session refers more specifically to the user interactions that are tracked by a Netscape Application Server application. The user's session with a web browser or other client software might start before the Netscape Application Server application begins tracking the user, and could continue after the application stops tracking the user.

Sessions are useful when you want to store information about each user's interaction with the application, as illustrated in the following examples:

To track session information, a base session class uses a specific Netscape Application Builder session interface (HTTPSession). Each time a particular servlet is executed during the session, the servlet can instantiate the base session, which accesses an HTTPSession interface provided by a Netscape Application Server. This is a view of the actual session information. The session ID ensures that all these session instances in fact point to the same data.

Note. The HTTPSession interface does not indicate what objects are stored in the session.

This section describes the following topics:

Using an AppResource Class
The application resource file stores session information specific to your Netscape Application Builder project. Servlets use sessions to store information about each user's interaction with the application. For example, a login servlet might create a session object to store the user's login name and password. This session data is then available to other servlets in the application.

Netscape Application Builder automatically creates a default base session, AppResource.java, which you can customize as you develop your application. This file stores code generated by Netscape Application Builder wizards and other property editors. The AppResource.java file stores information about how the project accesses the session. Specifically, it tracks string-based values generated by wizards and stores these values in the session and retrieves them from the session.

For information that describes how to specify which file serves as the application resource class for your project, see Setting Base Classes.

Modifying Session Variables
Netscape Application Builder also helps you to create and manage session variables for your application.

Session variables are used by many servlets in an application to store and access data that is shared throughout the application. They behave much like global variables do for an application; if you think of servlets as separate procedures and functions for an application, the session variables act (per user) as globally accessible data blocks that are shared across all servlets.

For example, a banking application can store the balance of the current account in a session variable; as the user executes a series of servlet requests, the balance is updated on the server by manipulating a session variable. When you define a session variable with Netscape Application Builder, the variable becomes automatically accessible for use by all Netscape Application Builder wizards where input fields are required. This mechanism makes it easy to pass session variables into other servlet requests or to a query parameter.

To modify your session variables, perform the following steps:

  1. Click the AppResource.java file.
  2. Select the Session Variables property in the Properties window.
  3. Expand this property to see a list of session variables.
  4. You can rename, delete, or add values to this list.
Netscape Application Builder automatically creates the accessor methods for the new session variable. For example, if you create a session variable called userName, Netscape Application Builder adds the getuserName() and setuserName() methods to the base session class. You can subsequently use these methods anywhere in your application code.

Using an appInfo.ntv File
The appInfo.ntv file stores the following session and servlet-specific information:

For a more information, see Application Configuration Information.

Inspecting the appInfo.ntv File via the Inspector
To edit the appInfo.ntv file, perform the following steps:

  1. Double-click the appResource.java file to open the editor.
  2. Right-click and choose the Properties menu item (or from the View menu, choose Properties; or select the Outline Tab View and double-click the AppResource line (the only line in the Outline view for appResource.java files), or, again, right-click and choose the Properties menu item.
  3. Using the Inspector, you should see the following editable items:

Accessing Data Sources via JDBC
In some situations, accessing a database directly from a servlet (via embedded JDBC) can be faster than accessing databases from EJBs. Fewer calls need to be made, especially if your application is spread across servers so that your EJBs are accessible only through the Java Remote Method Interface (RMI).

Use direct database service through servlets as little as possible. If you do provide database access from servlets restrict access to those situations where access is very short duration, the transaction is read-only, and you can take advantage of the new JDBC 2.0 RowSet class. If you choose to access a database from a servlet, use the new JDBC 2.0 RowSet interface to interact with a database.


Validation
You can specify whether or not to validate a parameter and the kind of validation to enforce in the Properties window:

  1. Highlight Parameter under Validation.
  2. Click the custom editor button.
  3. The following Edit property dialog box appears:
You can specify built-in validation and add or delete parameters to be validated.

In addition to specifying validation in the Properties window, you can provide user validation. User validation is validation written by the user. Typically, user validation is for inter-field dependencies (such as, orderDate < shippingDate < receivingDate), or field validation which requires data source access (or some other form of complex access); for example, validating credit cards.

You provide code to perform your own parameter validation within the servlet's actionHandler entry point. You must explicitly perform user validation at each entry point you want to check; otherwise, validation is not performed.


Additional Programming Considerations
The following sections provide additional information about servlets. For complete information, see the Programmer's Guide and the Foundation Class Reference.

Handling Servlet Output
Once the servlet has performed all of the associated presentation logic functions, it provides output back to the client. This output contains the results of any business logic activities (content) merged with an HTML JavaServer Page (layout).

Servlets can invoke JSPs to stream output back to the client. For more information about JSPs, see Presenting Application Pages with JSPs.

This section describes the following tasks associated with handling servlet output:

About GX Tags
GX tags are useful for declarative relational data binding, such as situations where a servlet outputs data from a result set to data-bound text fields. GX tags appear as HTML tags on templates. They are replaced with the data they describe at runtime. GX tags can appear either with standard HTML tag syntax (<GX ...>text block</GX>) or with an equivalent alternative syntax using the % character (%GX ...%text block%/GX%). text block refers to the text between the opening and closing tags <GX ...> and </GX>. For a more thorough description, see Creating Presentation Layout.

Calling JavaServer Pages
This section explains how to add JSP tags manually to stream response objects to a JSP via JavaBeans. In this situation, users need to manually add in-line Java code within the JSP tags to return the associated JavaBeans within the request object.

JSPs can be invoked from servlets via the RequestDispatcher() interface, as in the following pseudo code example:

RequestDispatcher dispatcher = 
getServletContext().getRequestDispatcher("JSPname.jsp"); 
dispatcher.forward(request, response);
The forward() method passes control of the interaction to the JSP, which builds the page and returns it to the client via the response object. Additionally, JSPs can be called directly from the client by using a URL

The JSP file is looked up in $AppPath/<directory path>. The file is invoked as if a request dispatcher had been invoked from the default application (see below).

Note. If you invoke a JSP but do not want to stream the default template, your actionHandler should return IServletErrorNumber.FAIL_DONT_STREAM_ERROR.

Using setDefaultTemplate() to Change the Output JSP
In many situations, you may need to specify the output JSP of an servlet at runtime. For example, you might want to reuse the same servlet to display the same information in two different applications. You can present the same information within two different pages by specifying different JSPs to use in the code of your servlet.

To set the default template associated with an servlet, use the setDefaultTemplate() method in your actionHandler. See the Java documentation for HttpServletRequest2. Setting the default template sets the JSP to which your BaseServlet object streams output. This occurs when your servlet's actionHandler returns.

 

© Copyright 1999 Netscape Communications Corp.