Certainly by now, everyone has heard of Microsofts Active Server Pages (ASP). It seems that, even if you havent played with ASP yourself, someone else has been telling you how cool ASP is and how easily you can code dynamic Web pages by using it. ASP is cool, and it is easy to code with it. The problem is that ASP is primarily geared to Microsoft operating systems.
JavaServer Pages (JSPs) are the cross-platform alternative to ASP and are just as cool and just as easy to code with as ASP. The basic idea behind JSP is that, instead of having a file that contains only static HTML, a JSP file contains static HTML alongside code that dynamically constructs HTML from application data. Figure 1 (page 66) shows a sample JSP file that was used to build the List Customers Web page shown in Figure 2 (page 66). The static HTML is obvious; you can see the and
tags at the top of Figure 1. It is also obvious that the Java code is nested between sets of <% and %> tags. Other than that, unless youre familiar with both HTML and Java, the implementation and processing of the JSP example warrant explanation. Thats what this article does: It covers the basic structure of a JSP file and describes the behind-the-scenes processing that builds a dynamic Web page from the JSP file.Page Compiling
First of all, realize that, in a JSP file, the Java syntax is embedded in HTML. JSP files are, by convention, named with a suffix of .jsp. When I renamed the JSP400.jsp file shown in Figure 1 JSP400.html and requested it from my browser, my browser displayed the page shown in Figure 3. None too impressive, what happened was that, when I requested the
.html file, the server simply sent the whole fileincluding the embedded Java codedown to my browser. But, when I requested the JSP400.jsp file (as I did in Figure 2), the server parsed and executed the embedded Java code, which listed customer information contained in the QCUSTCDT file in the QIWS library.
Actually, thats a lie or maybe just an oversimplification. What really happened when I requested JSP400.jsp was actually a little bit more complicated. When the server saw the .jsp suffix, it instigated what is known as the page compile process. The page compile process takes a JSP file and creates source for a Java servlet. That servlets Java code has static HTML code that comes from the JSP file along with the executable Java
logic. The server then compiles the Java servlet into a class and finally invokes the servlet class. In the case of the servlet generated from the JSP example shown in Figure 1, it opened a Java Database Connectivity (JDBC) object, retrieved a set of records, and then listed them using an HTML table. See the Editors Note at the end of this article for instructions on how to run this yourself.
Your first thought about the page compile process is probably performance bottleneck, but realize that, on subsequent JSP requests, the page compile does not take place unless the server senses that the JSP was modified since its associated servlet was last created/compiled. Also note that subsequent invocations use the same servlet instance. Through Javas excellent and efficient implementation of threads, a single servlet instance can handle requests from many clients.
Four Types of JSP Syntax
There are four basic types of JSP syntax as shown in Figure 4: directives, declarations, scriptlets, expressions, and comments. Actually, thats five, but comments arent really code, are they? Anyway, Ill describe each of them, and, if you know a little bit about Java, youll be able to understand the code in Figure 1. If you dont know Java, hang on; Ill describe the code for Figure 1 later in this article.
Directives, such as the first example in Figure 4 (page import), are identified by the at symbol (<%@). Directives are typically used to qualify the names of packages of Java classes you wish to use in your JSP. You can also use a directive to include output from HTML files, servlets, or other JSPs:
<%@ include file=relativeURL %>
Declarations, such as the second example in Figure 4, are identified by the exclamation point (<%!). Declarations are used to describe object variables that can be used in any of the Java code within a JSP file. All the browser-based requests for that same JSP share the values of the declared object variables. JDBC and AS/400 Connection objects are good candidates to be defined in a JSP declaration.
Scriptlets, such as the third example in Figure 4, are identified without any special characters after the <% tag. Scriptlets are where you place your code. The code in a scriptlet can be as complex as you want; scriptlets enable the full power of the Java language within a JSP file. Notice that the example scriptlet in Figure 4 retrieves a JDBC Connection object and then starts a code block with an if condition. But then, curiously, the scriptlet is terminated by the %> tag. Youll use this type of scriptlet all the time. Youll use it because youll want to break out of Java to be able go back to HTML syntax to format output.
Expressions, as shown in the fourth example in Figure 4, are identified by the equal sign (<%=). Expressions are used to place the results of a single Java statement into HTML. The expression example in Figure 4 outputs the customer number value, which was retrieved from an SQL result set, to the dynamic HTML.
Comments, shown in the fifth example in Figure 4, are identified by a set of double hyphens (<%-- and --%>) when you dont want the comment to be included in the dynamic HTML. When you do want your comment to be in the HTML that is downloaded to the browser, use the tags.
There are also a number of advanced JSP tags that this article does not describe. Specifically, they are jsp:forward, jsp:include, jsp:useBean, jsp:getProperty, and jsp:setProperty.
The Sample
With the description of the basic JSP tags complete, I can now overview the logic in the JSP example shown in Figure 1. It begins with standard HTML: ,
,
The next set of JSP code is a scriptlet. It begins by retrieving the Connection object from the getConnection method and then, with that connection, runs an SQL Select statement to get all the customers in the QCUSTCDT file. After the SQL result set is retrieved, the scriptlet abruptly ends so the JSP file can go back into HTML mode to define the beginning of an HTML table (a subfile in AS/400 terms). The
With the table and its headers defined, the JSP starts another scriptlet, which is simply the beginning of a while loop. And then its back into HTML, where the table row (
Another scriptlet, which contains a single curly brace, is used to close the while loop. This scriptlet is followed by the HTML end table () tag. The last scriptlet contains the closing operations for the result set and the JDBC statement as well as the catch clause that closes the try/catch block that was opened at the first scriptlet.
The JSP file is completed with the standard HTML tags that close the body and the HTML: and .
JSP: Just a Simple Page
This example is just a simple introduction to JSP. But, even though it is simple, the code has already begun to get complex. While it is true that you can use JSP to include all the HTML and Java code required to implement sophisticated Web pages, I recommend that, once you are comfortable with JSP, you look into the Model-View-Controller (MVC) architecture for developing Web applications. The MVC architecture separates presentation from programming by using a combination of JSP and servlets. For more information on MVC, see my article Application Modernization Nirvana in the January 2000 issue of MC and Alex Garrisons article Servlets: The New Application Architecture in the April 2000 issue of MC.
Editors Note
The examples in this article used syntax from the JSP 1.0 specification. I prefer the syntax of JSP 1.0 over JSP 0.91, and the JSP 0.91 syntax is quickly becoming obsolete. (WebSphere is one of the few platforms that still supports 0.91.) IBMs WebSphere 3.0 supports JSP 1.0, but earlier versions support only JSP
0.91. I suggest that, if you cant load WebSphere 3.0 on your AS/400, you work with JSP on your workstation using Suns free JavaServer Web Development Kit (JSWDK) from java.sun.com/ products/jsp/download.html. The JSWDK is known as a reference implementation, as it is used to test JSP technology. Visit www.midrangecomputing.com/mc and follow the Web tutorial in A PC-based JavaServer Pages Tutorial: Using Suns JavaServer Web Development Kit (JSWDK) to Test JSP and Servlets. That tutorial provides complete instructions for downloading Suns Web server reference implementation and IBMs Java Toolbox for the AS/400 as well as installation instructions for the Web server and how to test the JSP example shown in this article.
List Customers
<%@ page import="java.sql.*" %>
<%! Connection con = null;%>
<%!
public Connection getConnection() {
if (con != null) {return con;}
try {
Class.forName("com.ibm.as400.access.AS400JDBCDriver");
con = DriverManager.getConnection (
"jdbc:as400://YourDomainOrIP", "profile", "password");
} catch( Exception e) {
System.out.println("Error retrieving connection:" + e);
return null;
}
return con;
}
%>
<%
con = getConnection();
if (con == null) {
out.print("Sorry. Database is not available.");
return;
}
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(
"SELECT * FROM QIWS.QCUSTCDT ORDER BY LSTNAM");
%>
<%
Last Name
Init
Num
Street
City
ST <% while (rs.next()) { %>
<%= rs.getString("LSTNAM")%>
<%= rs.getString("INIT")%>
<%= rs.getString("CUSNUM")%>
<%= rs.getString("STREET")%>
<%= rs.getString("CITY")%>
<%= rs.getString("STATE")%>
<% } // while (rs.next()) %>
rs.close();
stmt.close();
} catch (SQLException e) {
out.println("SQL error : " + e);
}
out.flush();
%>
Figure 1: JavaServer Pages dynamically construct HTML on the host by using Java syntax.
Figure 2: HTML is used to format data retrieved with Java code.
Figure 3: If you change the .jsp suffix of a JSP file to .html, the Java code is not executed on the host; it is sent to the browser, which ignores it.
1) <%@ page import=java.sql.* %>
2) <%! Connection con = null;%>
<%! public Connection getConnection() {...} %>
3) <%
con = getConnection();
if (con == null) {
%>
4)
<%= rs.getString(CUSNUM)%>
5) <%-- comment not in HTML sent to browser --%>
Figure 4: Java code is embedded into HTML using special JSP tag sets.
LATEST COMMENTS
MC Press Online