08
Fri, Nov
10 New Articles

Bridge the Gap to Java with JSP

Web Languages
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Certainly by now, everyone has heard of Microsoft’s Active Server Pages (ASP). It seems that, even if you haven’t 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 you’re familiar with both HTML and Java, the implementation and processing of the JSP example warrant explanation. That’s 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 file—including the embedded Java code—down 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, that’s 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 servlet’s 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 Editor’s 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 Java’s 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, that’s five, but comments aren’t really code, are they? Anyway, I’ll describe each of them, and, if you know a little bit about Java, you’ll be able to understand the code in Figure 1. If you don’t know Java, hang on; I’ll 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. You’ll use this type of scriptlet all the time. You’ll use it because you’ll 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 don’t 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: , ,


, <BODY>, and <HEADER> tags. Then, since this example uses JDBC to access an AS/400 data file, a JSP directive is used to import the java.sql package. The sample then uses a declaration to declare a JDBC Connection object variable, con. Another declaration is then used to declare a complete Java method, getConnection. That method is later used to retrieve a JDBC Connection object. By using a declaration for the Connection object, the getConnection method creates that connection only once, thus relieving the server from the task of opening up a new connection for each user’s request for this JSP. Subsequent requests will reuse the same JDBC connection.</P><p><P>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 <th> tags indicate table headers.</P><p><P>With the table and its headers defined, the JSP starts another scriptlet, which is simply the beginning of a while loop. And then it’s back into HTML, where the table row (<tr>) and table data (<td>) tags are used to format a single record from the SQL result set. Look closely at each <td> line. Notice that each one contains a JSP expression. Each of those expressions is used to output the value of a data field from the SQL result set by basically using just the field name.</P><p><P>Another scriptlet, which contains a single curly brace, is used to close the while loop. This scriptlet is followed by the HTML end table (</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.</P><p><P>The JSP file is completed with the standard HTML tags that close the body and the HTML: </BODY> and </HTML>.</P><p><P><H3><B>JSP: Just a Simple Page</B></H3></P><p><P>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 Garrison’s article “Servlets: The New Application Architecture” in the April 2000 issue of MC.</P><p><P><SMALL><B>Editor’s Note</B></SMALL></P><p><P><SMALL>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.) IBM’s WebSphere 3.0 supports JSP 1.0, but earlier versions support only JSP<BR>0.91. I suggest that, if you can’t load WebSphere 3.0 on your AS/400, you work with JSP on your workstation using Sun’s 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 Sun’s JavaServer Web Development Kit (JSWDK) to Test JSP and Servlets.” That tutorial provides complete instructions for downloading Sun’s Web server reference implementation and IBM’s 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.</SMALL></P><p><P><SMALL><FONT COLOR #0000ff><CODE></CODE></FONT><BR> </SMALL></P><p><P><CODE><html><head><title>JSP JDBC/SQL Example

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");
%>

<% while (rs.next()) { %>

<% } // while (rs.next()) %>

Last NameInitNumStreetCityST
<%= rs.getString("LSTNAM")%><%= rs.getString("INIT")%><%= rs.getString("CUSNUM")%><%= rs.getString("STREET")%><%= rs.getString("CITY")%><%= rs.getString("STATE")%>
<%

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.


Bridge_the_Gap_to_Java_with_JSP05-00.png 404x288

Figure 2: HTML is used to format data retrieved with Java code.

Bridge_the_Gap_to_Java_with_JSP05-01.png 404x208

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.


Don Denoncourt

Don Denoncourt is a freelance consultant. He can be reached at This email address is being protected from spambots. You need JavaScript enabled to view it..


MC Press books written by Don Denoncourt available now on the MC Press Bookstore.

Java Application Strategies for iSeries and AS/400 Java Application Strategies for iSeries and AS/400
Explore the realities of using Java to develop real-world OS/400 applications.
List Price $89.00

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: