22
Fri, Nov
1 New Articles

Serving Up Host-based Java Apps

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

Anyone developing business applications in Java uses the Servlets API. Even though Sun introduced servlets just over a year ago, servlets are already a pervasive technology. Keep an eye on the URLs at the top of your browser for the next few weeks. A URL containing a qualifier with suffix .nsf indicates that a Lotus Domino application is driving the content. Directory name cgi-bin signifies that the application uses a legacy language with Common Gateway Interface (CGI). If “loading Java...” appears at the bottom of your browser’s screen, it doesn’t really matter, because you’re probably moving to another site because you don’t want to wait for the Java applet to download. Qualifier servlet is a sure sign that host-based Java servlet technology is driving the application.

Host-based Apps Rule

Java applets have fallen out of favor for Internet business applications. Applets were all the rage because they delivered client-side business applications over the Web. Web designers began using applets because they presented a graphical interface far superior to HTML, but they soon discovered that applets were fat clients because the code required to present that “superior” interface leaned toward obesity. Java servlets, on the other hand, are host- based. Servlets keep business logic on the server, and because the user interface for servlets is HTML, download speeds are not an issue. Some client-side logic may be required, but, more often than not, you can implement that client-side processing via a scripting language such as JavaScript or VBscript.

Dynamic generation of HTML with Java servlets is the same strategy CGI programmers have used for several years. CGI allows you to associate a URL request with a host program that can be implemented using your language of choice. However, on most platforms, each time a URL invokes a CGI program, that program is restarted, incurring normal expenses of security checks, memory allocation, and file opens. Once the program completes the request by returning an HTML response containing dynamically constructed information, that program instance is purged. Each subsequent invocation of the CGI program imposes a program initialization penalty on the server. Java servlets, in contrast, are not purged; the servlet instance remains available to the Web server for invocation by multiple clients.

Now, I must be honest. Earlier, I said “on most platforms” when noting the superiority of servlets over CGI, but the AS/400 is not an ordinary platform. Using a combination of activation groups and the Persistent CGI feature new with V4R3, CGI application performance on the AS/400 is far superior to CGI on most platforms. Application portability is the issue. With considerations such as security, caching, and clustering, Web server configuration is complicated. Consequently, many Web sites have multiple platforms that support a single application. For that reason, Web hosting needs to be portable. Servlets provide that portability. The AS/400 may be the best platform for back-end business applications, but front-end Web applications may not always be on the AS/400.

Web Logic

In specifying a URL on your browser, qualification is often to an HTML file within an explicit host directory: http://yourDomain/ home/level1/level2/SomeHtml.html. The host simply sends the HTML file from the location specified back to the client. Often, for simplicity and security, the host configuration maps a “logical” directory name to the real directory name, decreasing the length of the URL and concealing the real host directory name. CGI implementations also use the concept of a logical directory by mapping directory name cgi-bin to a library of host CGI programs. When the HTTP server sees cgibin, it executes the program name that follows the cgi-bin qualification. Web servers that support Java servlets, such as IBM’s HTTP Server for AS/400, map directory name servlet to a directory of Java servlets. In addition, as with CGI applications, the server invokes the Java servlet qualified by /servlet. Java servlets, like CGI programs, can be invoked from a URL request or as an action item on an HTML form. The page shown in Figure 1, for instance, is qualified by URL http://domainOrIP/servlet/Seminar. Once configured to enable Java servlets, IBM’s HTTP Server for AS/400 invokes the Java class Seminar, which is located in the AS/400 Integrated File System (AS/400 IFS)directory/QIBM/ProdData/IBMWebAS/servlets. (For detailed instructions on enabling Java servlets on V4R3 with PTF installation of IBM’s WebSphere for AS/400, see “WebSphere for AS/400 Setup” on AS/400 NetJava Expert Web Edition at www.midrangecomputing.com/anje/99/02. WebSphere V4R4 ships as a free but separately installed program product.)

The browser sends a URL request to the HTTP server in HTTP, which is the protocol of the Web. HTTP browser requests may include embedded HTML files but always provide request methods. When you enter a URL, the HTTP request method is GET, whereas an HTML form request uses the method POST. (For more information on HTTP, see “HTTP Undercover,” MC, July 1999.) When a Web server receives an HTTP GET request, the servlet engine invokes the doGet method of the Java servlet qualified in the URL. When the server receives an HTTP POST request, such as one sent from the entry form shown in Figure 1, the servlet engine invokes the doPost method of the servlet qualified by the action parameter of the HTML form tag. For example, notice the qualification of the Seminar servlet and the specification of a POST request method in the HTML in Figure 2:

The Servlet API

The example application in Figure 1 uses a Java servlet invoked by URL request http://domainOrIP/servlet/Seminar. The Seminar servlet dynamically builds the HTML response with the latest product information. That HTML response includes a form whose action is handled by the same Seminar servlet (although it can be a different servlet). The Seminar servlet is Java built atop the generic HttpServlet class. HttpServlet provides code implementations for common services, two of which I’ve already mentioned: doGet and

doPost. HttpServlet’s code implementations for doGet and doPost do nothing worthwhile. They’re in HttpServlet as placeholders to assure the servlet engine that all servlets, if only by order of object-oriented (OO) inheritance, have these methods. This is important because the servlet engine calls the doGet method based on a URL request and calls the doPost based on an HTML form action request.

If your servlet is to process an HTTP GET request from a URL, you must define a custom implementation of HttpServlet’s doGet method, and if your servlet is to process HTML forms, you must code a doPost.

HttpServlet also has a method called init. The servlet engine invokes a servlet’s init method the first time that servlet is requested, like an initialization subroutine in RPG. As you know from RPG programs, this initial processing can be handy. For servlets, you may want to code your init method to load a Java Database Connectivity (JDBC) driver and initialize JDBC connections or, if you prefer record-level access, open files as global fields declared in a Java class but not in a method of that class. Those JDBC connections or record-level access file opens then become available to all remote requests, saving the time required to connect to the database.

The Example

Code for the Seminar Java servlet is given in Figure 3. At Label A, the Seminar class extends the HttpServlet class. At Label B, the global fields of the Seminar class are declared. The values of these fields are accessible to all clients. The init method, at Label C, first calls its dad’s implementation of init. When you override HttpServlet’s init method, you need to invoke the parent’s version of init because it does some important initial processing that you need not code yourself. The Seminar class’s custom version of the init method then creates a vector (a dynamically sizable array) to hold the registrants. This servlet is coded for simplicity, so pretend that the init function has gone to DB2/400 to obtain the latest seminar locations and counts. Otherwise, I may as well code this information in a static HTML file. That’s the point of servlets: to present dynamic information over the Internet.

As Good as It Gets

The doGet method on Label D in Figure 3 has two parameters: HttpServletRequest and HttpServletResponse. The first parameter contains information about the request; the second contains the dynamically generated HTML response. I suggest you review the Java documentation for these two classes, as they have some powerful capabilities. Both of them, for instance, have methods that make using HTTP cookies a breeze. The request contains any parameter on the URL, but because the Seminar application uses no URL parameters, its implementation of doGet ignores the request parameter. At Label E, however, the response parameter is used. Think of HttpServletResponse as a handle to an HTML file containing the response to the user’s request. At Label E, the document resp.setContentType (“text/html”) tells HTTP that this file is to be transferred to that browser as text-based HTML. The next line at Label E receives a handle to the output stream. It’s like setting a record format in an RPG screen program.

The doGet method on Label F in Figure 3 dynamically constructs an HTML file. All HTML files are enclosed by and tags. They also have a head and body , so these obligatory tags are inserted into the response buffer. Label F then builds the body of the HTML file, inserting the .gif file for MC’s coffee cup and listing the fall dates for my Java seminars. Again, in a real application, this information comes from a database. At Label G, the input form is constructed. The input form contains a drop-down selection for the city of choice and a text field for the registrant’s name. The doGet code ends by closing the print writer, at which point the servlet engine sends the HTML response to the browser (see Figure 2).

Postage Due

Once the user selects a city, keys in a name, and clicks Register, the ACTION option of the HTML form tag instructs the Seminar servlet to process the HTTP POST request. Code for the doPost method is given in Label H of Figure 3. The doPost method has the same two parameters as doGet. Again, the content type is set, and a handle to the output writer is obtained. At Label I, the city and name parameters specified by the client are retrieved. Then, at Label J, after stuffing the obligatory HTML, HEAD, and BODY tags, doPost’s code checks whether registration is full. If seats are still available, doPost increments the array element of the global count field associated with the selected city. (A real application would update a database at this point.) Figure 4 shows the dynamic HTML content generated by doPost when Billy Briggs registers, and Figure 5 shows how it looks on Billy’s browser.

You Must Pool Your Resources

Obviously, Internet applications are more complex than my Seminar servlet, and industrial- strength servlets have more requirements. They must have some form of transaction control to ensure data integrity. For performance, they should have some form of database connection pooling. They also need a strategy to maintain state across the stateless HTTP. Transaction control can be enabled with JDBC transactions, record-level access commitment control, or Enterprise JavaBeans (EJB) transactions. You can code your own connection pool logic or use the connection pooling features included with most Web application servers, including IBM’s WebSphere. For such things as the Internet’s popular shopping cart metaphor, you can use either HTTP 1.1’s Session API or HTTP cookies. You can also add elegant state management features by employing EJB with your servlets. You may ask, “Isn’t embedding HTML into a Java servlet the same thing as describing screens in RPG?” That is a problem. It’s always better to separate screen design from program design. It’s even more important with Web applications because HTML design is becoming a profession unto itself. Business programmers can easily present information logically with HTML but don’t often have the time or training to make it pretty with graphics. Recently, Sun developed Java Server Pages (JSP), which separates programming logic from screen presentation, and because JSP is relatively new, it’s fortunate that WebSphere supports JSP.

Related Materials

• “HTTP Undercover,” Teresa Pelkie, MC, July 1999
• “WebSphere for AS/400 Setup,” Lisa Wellman, AS/400 NetJava Expert Web Edition, www.midrangecomputing.com/anje/99/02




Figure 1: When a Web server sees the servlet qualification on a URL, it invokes the named Java servlet.



MC Java Seminars



Fall '99 Seminar Dates



  • September 22-24 -- Las Vegas
  • October 18-22 -- Kansas City
  • November 15-19 -- Dallas
  • December 6-10 -- Phoenix

Online Registration



City:
 
Name:



Serving_Up_Host-_based_Java_Apps05-00.png 900x887







Figure 2: HTML forms can associate a Java servlet to process the user request.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

public class Seminar extends HttpServlet

{

A G H

I

J

String cities[] = {"Las Vegas", "Kansas City", "Dallas", "Phoenix"};
int count[] = {57, 48, 99, 100};
Vector registrants[] = null;

public void init(ServletConfig sc)
throws ServletException
{
super.init(sc);
registrants = new Vector[cities.length];
for (int i = 0; i < cities.length; i++) {
registrants[i] = new Vector();

}

B D

E

F

C

Figure 3: The Seminar servlet creates a registration form in its doGet method and processes that form in its doPost method.


Seminar Confirmation

Registration Confirmation


Thank you, Billy Briggs. Your registration is confirmed.

Figure 4: The HTML response from a servlet contains dynamic information.

resp.setContentType("text/html");
PrintWriter out = new PrintWriter(resp.getOutputStream());

String name = req.getParameter("name");
String city = req.getParameter("city");

out.println("");
out.println("Seminar Confirmation");
out.println("");
out.println("

Registration Confirmation

");

int iCity = 0;
while (cities[iCity].equals(city) != true)
iCity++;
if (count[iCity] >= 100) {
out.println("Sorry, the seminar is full in "+cities[iCity]);
} else {
count[iCity]++;
registrants[iCity].addElement(name);
out.println("Thank you, "+name+". Your registration is confirmed.");
}

out.println("");
out.println("");
out.close();

}

public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException

{

resp.setContentType("text/html");
PrintWriter out = new PrintWriter(resp.getOutputStream());

out.println("");
out.println("MC Java Seminars");
out.println("");
out.println("

"ALIGN=""Top"" WIDTH=500 HEIGHT=200>
");

out.println("

Fall '99 Seminar Dates

");
out.println("
    ");
    out.println("
  • September 22-24 -- Las Vegas");
    out.println("
  • October 18-22 -- Kansas City");
    out.println("
  • November 15-19 -- Dallas");
    out.println("
  • December 6-10 -- Phoenix");
    out.println("
");

out.println("

Online Registration

");

out.println(""); out.println("City: ");
out.println(" ");
out.println("Name: ");
out.println(""SIZE=20 MAXLENGTH=50>");
out.println("

");
out.println("

"VALUE=""Register"">");

out.println("");
out.println("");
out.close();

}

public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException

{ }

}




Figure 5: Whether you use Java servlets or RPG CGI, the point is to interact with the user.



Serving_Up_Host-_based_Java_Apps07-00.png 900x395
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: