YOUR FEEDBACK
More on the Software Assembly Question - Do Design Patterns Help?
Yanic wrote: Hi, > UML and MDA are being changed to be more data and doc...
SOA World Conference
Virtualization Conference
$50 Savings Expire May 23, 2008... – Register Today!


2007 West
GOLD SPONSORS:
Active Endpoints
Your SOA Needs BPEL for Orchestration
BEA
Virtualized SOA: Adaptive Infrastructure for Demanding Applications
Nexaweb
Overcoming Bandwidth Challenges with Nexaweb
TIBCO
What is Service Virtualization?
SILVER SPONSORS:
WSO2
Using Web Services Technologies and FOSS Solutions
Click For 2007 East
Event Webcasts

2008 East
PLATINUM SPONSORS:
Appcelerator
Think Fast: Accelerate AJAX Development with Appcelerator
GOLD SPONSORS:
DreamFace Interactive
The Ultimate Framework for Creating Personalized Web 2.0 Mashups
ICEsoft
AJAX and Social Computing for the Enterprise
Kaazing
Enterprise Comet: Real–Time, Real–Time, or Real–Time Web 2.0?
Nexaweb
Now Playing: Desktop Apps in the Browser!
Sun
jMaki as an AJAX Mashup Framework
POWER PANELS:
The Business Value
of RIAs
What Lies Beyond AJAX?
KEYNOTES:
Douglas Crockford
Can We Fix the Web?
Anthony Franco
2008: The Year of the RIA
Click For 2007 Event Webcasts
SYS-CON.TV
POWERBUILDER LINKS YOU MUST CLICK ON


Building JSP Applications with Jaguar CTS Part 3

Digg This!

Welcome back to JSP Corner. In this article we look at how to build a simple logon page that collects data through an HTML form and sends it to a JSP page for processing. This is a simple task that involves several aspects of Web development in JSP, including the retrieval of data from a request and page redirection.

The Application
A user of an e-music Web application needs to log on to the Web site in order to store items in a cart and then purchase them. Other techniques can be used instead of forcing the user to log in first, such as storing the user's shopping cart in a cookie on the user's machine and waiting for the user to click a purchase link before gathering shipping and billing data. The shipping and billing data can then be stored and accessed via a user ID and password or entered for each of the orders the customer places.

For simplicity's sake we'll use the same technique used in the original e-music application built by Sybase with PowerDynamo. Using the logon page the user types in a user name and password. These pieces of data are collected in an HTML form. When the user clicks on the Submit button, renamed Logon, the browser sends the information to our JSP page, validateLogon.jsp. This page is responsible for determining whether the user name and password are valid. If the user is valid, the request is redirected to the Home.jsp page, otherwise the request is directed to the LogonError.htm page. This application flow is illustrated in Figure 1. The LogonError.htm page contains a link back to the Logon.jsp page.

Building the Logon.jsp Page
The Logon.jsp page is a simple HTML page that's written as a JSP page so that when the password is mistyped, we can keep track of the user name using session management. When the user clicks the link on the LogonError.htm page to try to log in again, the previously typed user name will appear in the form. We won't focus on the code to handle this feature in this article; our main focus is how to write some Java code in a JSP and handle page redirection.

The main structure in the Logon.jsp page is an HTML form. The basic outline of the HTML form is shown below, and the entire page is shown in Listing 1.

<FORM ACTION="validateLogon.jsp" METHOD="POST">
<INPUT TYPE=text SIZE=10 NAME="userID" >
<INPUT TYPE=password SIZE=10 NAME="userPwd">
<INPUT TYPE=submit SIZE=10 NAME="OK" VALUE="Logon">
</FORM>
When the Logon.jsp page is loaded in a browser, the HTML form will be rendered similar to the screenshot shown at the top of Figure 1. The location the data is sent to is specified in the ACTION attribute of the FORM tag, and how the data is sent is specified in the METHOD attribute. The two valid values of the METHOD attribute are GET and POST. The value of POST is more commonly used since it has no limits on the amount of data that can be sent.

When the Submit button is pressed, the browser will automatically create a URL that calls the specified resources in the ACTION attribute, in our case the validateLogon.jsp page, passing the input typed into the various INPUT tags contained in the form. In our case it's the INPUT tags named userID and userPwd. The URL created by the browser would look something like this:

http://localhost:8080/eMusic/validateLogon.jsp?userID=mike&userPwd=mike
When we retrieve the information from the URL we don't need to worry about whether the data was passed using the GET or the POST method or how the browser stores the data in the URL. We simply need to know the names of the INPUT tags.

Building the validateLogon.jsp Page
Most of the interesting programming is done in the validateLogon.jsp page shown in Listing 2. In this page we use a simple algorithm to validate our users by comparing the user ID to the password and seeing if they're equal, so we won't complicate the example with JDBC code. Later we can replace the validateLogon.jsp page with a Java servlet that connects to a database and compares the values in a database table.

As we build our JSP page to handle logon validation, it's important to note that proper application partitioning places presentation tasks in a JSP page, while servlets and Enterprise JavaBeans (EJB) are designed to handle business-processing tasks such as logon validation. We're breaking this rule right now to showcase JSP development.

One of the first new tags (page directives were covered in Part 1 [PBDJ, Vol. 8, issue 9]) that we see in this file is the <%-- tag, which denotes a comment in a JSP page. Comments can be inserted as follows and should require no further details:

<%-- comment goes here --%>
The next set of tags that we encounter in the JSP page are the scriptlet tags denoted by the <% and %> delimiters. All the content between the <% and %> delimiters is handled as Java code. The Java code in a JSP page can be written to do just about anything any other server-side Java class can do. We'll be looking at Java code a lot in this and future articles; however, it's not the intent of this article to teach the nuances of programming with the Java language but rather to showcase the various techniques and tags used with JSP by building a simple application.

The following is an example of writing some simple Java code as a scriptlet; this page returns the server's date and time as an HTML page:

<html>
<body>
<%
// Create a new date object and write it out
java.util.Date now = new java.util.Date();
out.printin(now);
%>
</body>
</html>
Everything between the <% and %> tags is considered Java code, including the Java comments, // and /* ... */. When writing Java code in a scriptlet block it's important to understand that nothing is actually generated as part of the page's response unless it's expressly written using one of the write, print, or println methods of the out object reference. The out object is of type javax.servlet.jsp.JspWriter. This object represents the output stream for the JSP page that contains the data that will be sent to the browser. The JspWriter class extends the java.io.Writer class. The out object reference is known as an implicit object because every JSP page has access to the object without creating it first.

Compare the JSP scriptlet to the JSP expression (introduced in Part 1), which is opened with the starting delimiter <%= and closed with the %> delimiter. This tag accepts only a Java expression whose output is written directly to the page's output stream. Our example, which writes out the server's date and time, can be rewritten with an expression tag; however, most scriptlets involve multiple lines of Java code that can't be converted into a single Java expression.

<html>
<body>
<%=new java.util.Date() %>
</body>
</html>
The Request Object
In our validateLogon.jsp page we need to retrieve the user ID and password that were typed in by the user and sent via an HTML form. We do this using another implicit object, the request object. This object represents the HTTP request that called the page now running on the server. It encapsulates all the data including the URI path, HTTP headers, cookies, and page parameters. The request object implements the javax.servlet.http.HttpServletRequest interface. The methods of the request object that we're interested in retrieve the page parameter data (see Table 1).

Each piece of data that's sent as part of the URL is stored as a name/value pair in the request object. Given the URL generated from our HTML form we have the following two page parameters:

userID=mike
userPwd=mike
The code to get the user ID and password from the request object is straightforward:

String userID = request.getParameter("userID");
String password = request.getParameter("userPwd");
Once we have the page parameter values we can perform operations on them. In our case we compare the values to see if they're equal.

Forwarding the Request
The validateLogon.jsp page doesn't have any presentation logic itself. If this page were allowed to return control to the browser we would get a blank screen. Once the user ID and password have been authenticated, this page needs to pass control to either the Home.jsp page or the LogonError.htm page, both of which are responsible for displaying the appropriate presentation to the user.

Passing control can be done one of three ways: forwarding, redirecting, or including. Forwarding a request involves transferring control from the originator page to the target page. The transfer of control to the target is permanent. The target can be a static HTML page, another JSP page, a servlet, a CGI program, or any other valid Web resource. The contents and output of the originating page are discarded and the results of the target page are returned to the browser. Forwarding a request is done at the server level so the user doesn't notice the transfer of control (see Figure 2).

Redirecting a request involves permanently transferring control from the originator page to the target page. However, in this case the originating page sends a special status code and header back to the Web browser that tells it to request the target page from the server. The effects are similar to forwarding a request except that the transfer of control is not handled at the server level and requires a round-trip to the client.

Including a request involves temporarily transferring control from the originator page to the target page. This transfer is done at the server level where the originating page includes the generated output of the target page. The target is executed (if it's an executable resource like a JSP or servlet) on the server and its generated contents are placed into the originating document where the include tag was placed. The originating document regains control and continues processing.

In our example we're forwarding the request to partition the processing (login validation) away from the presentation (the welcome page or the error page) as well as to avoid an extra network call between the client and the server.

Forwarding a request can be handled with the JSP action tag or by using the RequestDispatcher object. The JSP forward tag is recommended as it requires less Java code. The JSP tag is shown below:

<jsp:forward page="target" />
The page attribute is used to specify the target Web resource. The JSP action tags, including the forward tag, use XML syntax and must end properly with the /> instead of the typical > used to close an HTML tag. The transfer of control is done when the JSP page execution reaches the tag. The following code sample shows how to combine a scriptlet with a JSP action tag to make the forwarding of control conditional.

<%
if (userID.equals(password)) {
%>
<jsp:forward page="Home.jsp" />
<%
} // end of if
%>
Notice that the end of the if-statement, denoted by the }, is terminated in the second scriptlet since the JSP forward tag is just a tag and can't be contained in a scriptlet block. The ability to separate scriptlet code makes HTML generation easy since HTML tags don't have to be written out in strings of embedded Java code, allowing visual HTML editors to be used to create HTML pages.

The javax.servlet.RequestDispatcher is an interface implemented by the servlet/JSP container vendor. A reference to the RequestDispatcher object can be acquired using the getRequestDispatcher method on the request object instance that's passing in the URL to the target. Once we have a reference to the RequestDispatcher object we call the forward method, passing the request and the response objects to actually transfer control to the target.

<%
if (userID.equals(password)) {
request.getRequestDispatcher("Home.jsp").forward(request, response);
}
%>
Notice in the code sample above that the if-statement is fully contained within a single scriptlet as compared to the previous example.

The Home.jsp Page
When the user types in a valid user ID and password, the validateLogon.jsp page forwards the user to the Home.jsp page. We won't discuss this page here as it's the topic of our next article. For now you can use a simple HTML page that displays a message, such as "Welcome," to indicate a successful logon attempt.

The LogonError.htm Page
When the user types in an invalid user ID and password the validateLogon.jsp page forwards the user to the LogonError.htm page (see Listing 3). This is a simple HTML page that displays a message, "Invalid User ID or Password," and a link that will take the user back to the Logon.jsp page to try again.

Wrapping Up
That's how you develop pages that allow logon attempts to the e-music Web site. It also introduces several important JSP tags, including the scriptlet and the JSP forward tag. Several aspects of JSP development were not addressed in this article, such as session management, thread safety, and buffering of the response output; these all impact how our application runs. We'll cover these topics in future articles as we continue to build our application. Until next month, happy coding.

About Mike Barlotta
Background Information: Michael Barlotta is the Director of Technology at AEGIS.net Inc (www.AEGIS.net). Mike is a Sun Certified Java Programmer and is recognized as an expert on the Sybase application server EAServer (Jaguar CTS), mentoring clients and speaking at conferences on the topic. He is the author of several books including Taming Jaguar and Jaguar Development with PowerBuilder 7 (both by Manning Publications). Be sure to check out Mike’s Web site www.TamingJaguar.com.

PBDJ LATEST STORIES . . .
3rd International Virtualization Conference & Expo: Themes & Topics
From Application Virtualization to Xen, a round-up of the virtualization themes & topics being discussed in NYC June 23-24, 2008 by the world-class speaker faculty at the 3rd International Virtualization Conference & Expo being held by SYS-CON Events in The Roosevelt Hotel, in midtown
The PB Future: More on Graphs in PowerBuilder 11.5
Last week I posted a screen shot of the new 3D Rendering capabilities being added to some of the 3D graphs in PowerBuilder 11.5. It was met with mixed reviews on the PowerBuilder Futures newsgroup (forums.sybase.com) so I went back to the drawing board to see what I could come up with.
BluePhoenix Expands Modernization Collaboration with Microsoft
BluePhoenix announced that it has expanded its collaboration with Microsoft on legacy modernization projects. The collaboration provides customers moving their applications or databases to .NET-based environments the best in both modernization services and technical support. BluePhoeni
Sybase PowerBuilder Delivers AJAX and .NET Enhancements Enabling Rich Internet Application Development
Sybase announced that AJAX development capabilities and further Microsoft .NET enhancements have been added to the latest version of Sybase PowerBuilder 11, the premier 4GL rapid application development (RAD) tool. PowerBuilder 11.2 represents another milestone in the PowerBuilder road
PowerBuilder 11.2 Released: Sybase's Flagship IDE
Sybase has released the production version of its flagship .NET development tool - PowerBuilder version 11.2. This latest release of its premier IDE for RAD includes not only standard fixes but also a good list of new features. Here is the 'Coles Notes' version of these new features.
PowerBuilder Takes You To .NET
In June of 2007, Sybase released PowerBuilder 11. PowerBuilder developers can now deploy PowerBuilder components as .NET Assemblies or as .NET Web Services. A PowerBuilder developer can now create these .NET resources so that those who develop .NET solutions can benefit from PowerBuild
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

SYS-CON FEATURED WHITEPAPERS

ADS BY GOOGLE
BREAKING POWERBUILDER / SYBASE NEWS
Sybase and Sun Set Guinness World Record for World's Largest Data Warehouse
Sybase, Inc. (NYSE:SY), the largest enterprise software and services company exclusively