12
Tue, Nov
6 New Articles

CGI, the Apache Web Server, and HTML Data Merging

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

Configuring the Apache Web server isn't too difficult as of V5R1 and later. Previously, it was, shall we say, "challenging."

To configure a new Apache server instance, you need to start a preinstalled "administrator" instance of the Web server. IBM ships this with your iSeries as HTTPSVR(*ADMIN) on the STRTCPSVR command. To start the administrator's instance, issue the following CL command:

 STRTCPSVR SERVER(*HTTP) HTTPSVR(*ADMIN)

After a few seconds, the *ADMIN instance will be visible via the WRKACTJOB's command. To view the instance along with any other running Web servers, run the following CL command:

 WRKACTJOB SBS(QHTTPSVR)

The job named ADMIN is the *ADMIN instance of the Web server. The *ADMIN instance waits on port 2001 and routes you to the IBM-supplied Web pages that allow you to configure and manage other instances of the Web server.

To load up the administrator instance, type the following into a browser: http://xxxxx:2001.

Here, xxxxx is either the IP address of the iSeries running your Web server or the equivalent domain name.

Follow the relatively easy-to-use prompts to create a new Web server. If you already have a Web server configured, use the prompts to manage that Web server.

Since the focus of this series of articles has been CGI RPG IV programming, I am only interested in the configuration statements that relate to CGI programming. (Click here for more information on the entire set of Apache configuration directives. I would bookmark that page as it proves invaluable during the initial configuration period.)

The first thing you need in your Web server configuration file is a Listen statement. For example:

Listen 198.1.2.3.4

This tells the Web server what IP address this configuration applies to. You can optionally add a port number, as follows:

Listen 198.1.2.3.4:1024

The port 1024 is now assigned to this configuration. You can use just about any port you'd like, but some are reserved. For example, port 80 is used for the standard configuration (the one that you run your Web site from), and ports 2001 and 2010 are used for the administrator's instance.

To get CGI running for this instance, you need to add the ExecCGI statement, as follows:

 
 Options +ExecCGI 
 Order Allow,Deny 
 Allow From All 
 

Many Apache directives use multiple lines to specify their values. In the example above, the MYCGI directory has CGI enabled and allows users to use the content of that directory. However, in the old CERN Web server, to enable CGI program mapping, you would code the following:

 MAP /CGI-BIN/*  /CGI-BIN/*.PGM

Then, to enable/run the CGI program, the following statement would be required:

 EXEC /CGI-BIN/* /QSYS.LIB/MYCGI.LIB/*

The following are the equivalent statements in the Apache configuration:

 MapMatch ^/CGI-BIN/(.*) /CGI-BIN/$1.PGM                  
 ScriptAliasMatch ^/CGI-BIN/(.*) /QSYS.LIB/MYCGI.LIB/$1  

In the examples above, the AS/400 library named MYCGI is set up to allow CGI programs to be run from it.

CGI Programming, Part 3: Merging Data with HTML

In my last article, we talked about sending HTML to the browser. I also showed you how to use a very primitive scan/replace routine to merge data with the HTML. This week, I want to illustrate how you can use substitution tokens to easily merge data with HTML.

HTML is a static piece of text. It does not change unless you write a JavaScript to dynamically modify what is displayed in the browser. You can use other languages, such as Java, and Microsoft's Internet Explorer allows you to embed programs in the browser window (which is the source of most IE-based viruses, I might add).

But other that than, you need to insert the data in your browser using a CGI language. Since this is the RPG Developer newsletter, I won't show you how to do that with Net.Data or Java; instead, I'll illustrate how to merge your live data using HTML and good old RPG IV.

The term "token" has been around for decades, and it is used today in computer programming to represent a symbol found on a statement. It is a generic name for a "thing" on a source line.

For example, how many tokens are in the following RPG IV statement?

  C        EVAL     DISCOUNT = QTY * PRICE / 10

There are either seven or eight, depending on how you count. If you include the opcode, there are eight. Each field is a token, as is each math operator, and the equals sign (=) is also a token.

To insert data in HTML, we have to come up with a scheme to substitute a token for some useful data; otherwise, we would have a difficult time to say the least.

We have a couple of models to steal ideas from; one is the old System/36 OCL. It used ?1? tokens to represent parameter values. Another is the System/38 messaging system, still used today on iSeries and i5 platforms. It uses &1 tokens to represent substitution values in the form of message data.

From these two models, we learn that we need some type of relatively unique token capability along with an ability to uniquely identify each token. Numbering tokens is probably out of the question, as HTML pages can have huge amounts of data added to them, far beyond the ability to manage numeric tokens. So that leaves us with alphanumeric tokens. Tokens also need some type of symbol that makes them stand out from the rest of the text.

Mel Rothman of IBM Rochester (now retired) implemented a substitution token schema for HTML when he was building the CGIDEV2 library several years ago. This schema has since been used in the contemporary CGILIB service program and continues to be popular with the CGIDEV2 library.

The Rothman schema is based on an alphanumeric token ID surrounded by unique symbols that identify each token. The symbols he chose are illustrated below:

To begin a token ID name: /%

To end a token ID name: %/

To specify a substitution token in your HTML, you specify /%, followed by the token name, followed by %/. For example:

Company name:  /%CMPNAME%/

The token ID is /%CMPNAME%/, and it is your job to replace that token with some real data, presumably the real company name.

Suppose the company name you wanted to replace it with is Rocketplane, Ltd. The resulting HTML would look like this:

Company name:  Rocketplane, Ltd.

The CGILIB service program (as well as the CGIDEV2 library) makes this kind of substitution possible by handling all the scan/replace functionality for you. You simply load the HTML source code into an internal work buffer and then set each substitution token's value using an easy-to-call subprocedure. For example:

C                   callp     cgiSetVar('CMPNAME':'Rocketplane, Ltd.')

To make things even more dynamic, you might read a record from a database file and then call cgiSetVar(), as follows:

C     CUSTNO        CHAIN     CUSTMAST
C                   if        %Found()
C                   callp     cgiSetVar('CMPNAME':%TrimR(CMPNAM))
C                   endif

Note the use of the %TRIMR() built-in function to avoid sending excess blanks to the browser. While the browser would delete them anyway, line traffic is increased, so %TRIMR is used to avoid sending excess blanks.

The HTML needed to display a full customer record might appear in the HTML editor, such as Microsoft FrontPage 2003, as follows:

http://www.mcpressonline.com/articles/images/2002/CGI07210400.png

Figure 1: Here's your HTML layout view. (Click images to enlarge.)

The source for this HTML table would be as follows:


  Company:
  
 
 
  Contact:
  
 
 
  Address:
  
 
 
  City:
  
 
 
  State:
  
 
 
  Zip Code:
  
 
 
  email:
  
 

 
/%CMPNAME%/
/%CMPATTN%/
/%CMPADDR%/
/%CMPCTY%/
/%CMPSTE%/
/%CMPZIP%/
/%EMAIL%/

Figure 2: This HTML table source shows the substitution tokens.

To prepare the HTML by merging the data from a database with the HTML, you could use the following RPG IV code:

     C     CUSTNO        CHAIN     CUSTMAST
     C                   if        %Found()
     C                   callp     cgiSetVar('CMPNAME':%TrimR(cmpnam))
     C                   callp     cgiSetVar('CMPATTN':%TrimR(cmpattn))
     C                   callp     cgiSetVar('CMPADDR':%TrimR(cmpaddr))
     C                   callp     cgiSetVar('CMPCTY':%TrimR(cmpcty))
     C                   callp     cgiSetVar('CMPSTE':cmpste)
     C                   callp     cgiSetVar('CMPZIP':cmpzip)
     C                   callp     cgiSetVar('PHONE':%EDITW('0(   )&   -    ')
     C                   callp     cgiSetVar('EMAIL':%TrimR(email))
     C                   endif

Figure 3: This RPG IV source uses CGILIB to merge data with HTML.

Once the above RPG IV code runs, the HTML will be ready to send to the browser. It will appear in the browser (once cgiWrtSection() is called) as illustrated in Figure 4.

http://www.mcpressonline.com/articles/images/2002/CGI07210401.png

Figure 4: And now, here's your HTML page after substitution variable assignment using CGILIB.

Merging live data with HTML does not need to be rocket science. Simple helper tools such as CGIDEV2 and CGILIB can make writing with CGI a pleasure.

Now get back to work.

Bob Cozzi is a programmer/consultant, writer/author, and software developer. His popular RPG xTools add-on subprocedure library for RPG IV is fast becoming a standard with RPG developers. His book The Modern RPG Language has been the most widely used RPG programming book for more than a decade. He, along with others, speaks at and produces the highly popular RPG World conference for RPG programmers.

BOB COZZI

Bob Cozzi is a programmer/consultant, writer/author, and software developer. His popular RPG xTools add-on subprocedure library for RPG IV is fast becoming a standard with RPG developers. His book The Modern RPG Language has been the most widely used RPG programming book for more than a decade. He, along with others, speaks at and produces the highly popular RPG World conference for RPG programmers.


MC Press books written by Robert Cozzi available now on the MC Press Bookstore.

RPG TnT RPG TnT
Get this jam-packed resource of quick, easy-to-implement RPG tips!
List Price $65.00

Now On Sale

The Modern RPG IV Language The Modern RPG IV Language
Cozzi on everything RPG! What more could you want?
List Price $99.95

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: