Previous Contents Index DocHome Next |
Application Builder 6.0 iPlanet Application Builder User's Guide |
Chapter 5 Creating Presentation Logic
This chapter describes the concepts and tasks associated with creating the presentation logic for web applications and describes how to use iPlanet Application Builder's Java editor and Properties window to customize servlets.The following topics are described in this chapter:
About Java Servlets
Working with Session Management
Accessing Data Sources via JDBC
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:
They are an alternative to a CGI script.
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.They are invoked by a browser/client request.
They communicate using request and a response objects.
They output content via HTML streaming.
They simplify HTTP programming.
They control the application by specifying the flow of control, for example, which enterprise components to activate, what to cache, and which HTML pages or JSP files to invoke.
For a more in-depth description of how to design and create servlets programmatically, see the Programmer's Guide.
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 bythe servlet's doGet() and doPost()methods. 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, see "Creating 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:
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 and Editing JDBC RowSet Objects.
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).iPlanet 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, see "Creating 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. iPlanet Application Builder 6.0 has a set of JSP extended tag libraries. The wizard generated JSPs make use of these libraries for taks like database access. These libraries 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.By default, the JSPs generated through the JSP wizard are automatically registered. However, JSPs generated by all other wizards are not registered because they always have a registered servled associated with them that forwards the request object to the JSP for presentation.
For more information about JavaServer Page, see "Creating Presentation Logic."
Servlets
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 iPlanet 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 doGet() and doPost() methods.
If successfully handled, the servlet processes the output, most often by calling a JSP page. The default page is stored in the generated servlet as _defaultTemplate. The servlet then returns the output page to the user.
Creating and Editing Servlets
iPlanet 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 iPlanet 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.
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 Wizards
Creating Servlets via the Wizards
To create your iPlanet Application Server servlets using wizards, perform the following steps: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. iPlanet 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 iPlanet Application Builder tools.The following table maps the specific servlet components you can edit to the associated iPlanet Application Builder servlet editor tool.
Table 5-1 A Sampling of Servlet Components Mappings
The Properties editor for a servlet specifies properties that are set when you create the servlet via a wizard. You can change the initial parameters, caching information, validation parameters, through the project meta editor. For more information about these properties, see the Programmer's Guide.
Importing Servlets
To import a servlet, perform the following steps:
Copy the servlet file to a directory under the iAS root.
iPlanet Application Builder places the servlets in the correct location in the project tree, depending on whether the servlet is source or compiled code.Select Import Servlet(s) from the Project menu.
Select the servlet file, either by navigating or by entering the file name, and click Add.
Registering, Compiling, and Testing Servlets
Once you have created your Java objects, you can use iPlanet 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 Session Management
A session is a continuous series of interactions between a user and a iPlanet 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 iPlanet Application Server application. The user's session with a web browser or other client software might start before the iPlanet 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:
Record a history of which pages the user has visited during the session.
To track session information, a base session class uses a specific iPlanet 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 iPlanet 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.Increase security by requiring the user to log in to a secured session before running certain portions of the application.
In an online shopping application, keep track of items in the user's shopping cart.
This section describes the following topics:
Storing Session Variables at Design Time
Storing Session Variables at Design Time
The project file (*.iab) stores session information specific to your iPlanet 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.
Modifying Session Variables
iPlanet 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 iPlanet Application Builder, the variable becomes automatically accessible for use by all iPlanet 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:
Select the Project you want to modify.
Right-click to display a pop-up menu, and select Project Metadata ...
Select the Session Variable tab from the Metadata Editor window.
Add or remove variables from the list of design time session variables.
- The Variable Type column of this test is used to typecast the object returned from the session at runtime.
Validation
You can specify whether or not to validate a parameter and the kind of validation to enforce in the Servlet Meta Editor:
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.
Servlet Parameter Validation
A typical request-response cycle goes through several phases, the first of which is the checking required to ensure that the user has supplied all the correct input, and that they are properly authenticated for the access they require.Note that this validation is not trying to solve complex validation such as credit checks, although it is possible to do so.
Validation Requirements
The ValidationRequired flag for the servlet should be set to true.Each parameter needs to be identified and have at least the following attributes:
Session attribute or an input parameter
These fields are identified in the following Servlet Meta Editor Parameters tab:Class and Method to call in that class to determine the validity of the parameter
Optional format (for numbers and dates)
Definition of how errors should be handled including:
The validation scheme itself needs a URL to call when errors have been accumulated. An error handler at the servlet level should be set.
Additionally, one servlet may perform different functions. You could create a servlet to perform a search/insert/delete against a particular data source, and another server performing different functions. While the parameters for both servlets may have the same requirements, the list of which parameters to validate would be different depending on the entry points. So, along with a list of parameters, a list of ParamGroups must be identified with each event mapping to a list of parameters to validate.
Note Exposing the class:method pairs for validation give you the ability to add reusable validation components.
Parameter information is generated in the Login, Input, and Results wizard.
For more information about iAS specific DTD, see the Programmer's Guide.
Parameter and Parameter Groups
To enable servlet parameter validation:You can specify an error handler at the servlet level as well as the parameter level. The parameter error handler can be specified as a JSP, servlet, or log file.
In the following example, if param-error-handler is specified as a log, the error handler at the servlet level is used (Error.jsp).
The first servlet entry (Errorjsp.jsp) is a registered JSP for error handling.
The second servlet entry (ErrorServlet) is a registered servlet for error handling.
The third servlet is TestParamGroup whose parameters are grouped by ParamGroups and are to be validated.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ias-web-app PUBLIC `-//Sun Microsystems, Inc.//DTD iAS Web Application 1.0//EN'
`http://www.iplanet.com/j2ee/dtds/IASWebApp_1_0.dtd'>
<ias-web-app><servlet>
<servlet-name>Errorjsp</servlet-name>
<guid>{86422ba5-15a8-11d4-b65a-005004b1b6f4}</guid>
<servlet-info>
<sticky>false</sticky>
<encrypt>false</encrypt>
<number-of-singles>10</number-of-singles>
<disable-reload>false</disable-reload>
</servlet-info>
</servlet><servlet>
<servlet-name>ErrorServlet</servlet-name>
<guid>{86422ba3-15a8-11d4-b65a-005004b1b6f4}</guid>
<servlet-info>
<sticky>false</sticky>
<encrypt>false</encrypt>
<number-of-singles>10</number-of-singles>
<disable-reload>false</disable-reload>
</servlet-info>
</servlet><servlet>
<servlet-name>TestParamGroup</servlet-name>
<guid>{86422ba4-15a8-11d4-b65a-005004b1b6f4}</guid>
<validation-required>true</validation-required>
<error-handler>Error.jsp</error-handler>
<servlet-info>
<sticky>false</sticky>
<encrypt>false</encrypt>
<number-of-singles>10</number-of-singles>
<disable-reload>false</disable-reload>
</servlet-info><parameters>
<param>
<param-name>one</param-name>
<input-fields>
<input-required>true</input-required>
<input-rule>com.iplanet.server.servlet.extension.
validate.ValidationUtils.validateAlphabetic</input-rule>
<in-session>false</in-session>
<param-error-handler>ErrorServlet</param-error-handler>
</input-fields>
</param><param>
<param-name>two</param-name>
<input-fields>
<input-required>true</input-required>
<input-rule>com.iplanet.server.servlet.extension.
validate.ValidationUtils.validateInteger</input-rule>
<in-session>false</in-session>
<param-error-handler>ErrorServlet</param-error-handler>
</input-fields>
</param><param>
<param-name>three</param-name>
<input-fields>
<input-required>true</input-required>
<input-rule>com.iplanet.server.servlet.extension.
validate.ValidationUtils.validateInteger</input-rule>
<in-session>false</in-session>
<param-error-handler>log</param-error-handler>
</input-fields>
</param><param>
<param-name>four</param-name>
<input-fields>
<input-required>true</input-required>
<input-rule>com.iplanet.server.servlet.extension.
validate.ValidationUtils.validateInteger</input-rule>
<in-session>false</in-session>
<param-error-handler>log</param-error-handler>
</input-fields>
</param><param>
<param-name>five</param-name>
<input-fields>
<input-required>true</input-required>
<input-rule>com.iplanet.server.servlet.extension.
validate.ValidationUtils.validateInteger</input-rule>
<in-session>false</in-session>
<param-error-handler>Errorjsp.jsp</param-error-handler>
</input-fields>
</param>
</parameters><param-group>
<param-group-name>update</param-group-name>
<param-input>one</param-input>
<param-input>two</param-input>
<param-input>three</param-input>
</pram-group><param-group>
<param-input>four</param-input>
<param-input>five</param-input>
</param-group>
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.
Creating and Editing JDBC RowSet Objects
A row set is an object that encapsulates a set of rows retrieved from a database or other tabular data store, such as a spreadsheet. To implement a row set, your code must import javax.sql, and implement the RowSet interface. RowSet extends the java.sql.ResultSet interface, permitting it to act as a JavaBeans component.For more information about the RowSet interface, see the Programmer's Guide.
Setting Data Connections
You must specify a data connection when you run the database wizards. The wizard prompts you for the following information:
Table 5-2 Data Connection Wizard Prompts
The database driver with which to connect to the data source. Choose from one of the following drivers:
The connection information is stored in an xml file whose name consists of the data source name and the suffix .props. For example, the properties file for the cdx database is cdx.props. You can locate the xml file in the Connections folder.
This is a text file, containing one element for each property. To edit the file, double click on the file name in the Connections folder. The file appears in the editor window. You can make changes to property values as desired.
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 or JavaServer Page (layout).Servlets can invoke JSPs to stream output back to the client.
Calling JavaServer Pages
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
Previous Contents Index DocHome Next
Copyright © 2000 Sun Microsystems, Inc. Some preexisting portions Copyright © 2000 Netscape Communications Corp. All rights reserved.
Last Updated April 28, 2000