23
Tue, Apr
0 New Articles

Reconcilable Differences

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

Java servlets have taken the Web by storm. In a period of about 12 months, Sun Microsystems’ servlet technology has been widely adopted as a standard for host-based Internet applications. In “Serving Up Host-based Java Apps” (MC, August 1999), I showed how Sun’s servlet technology allows you to develop server-side Java applications that respond to browser requests by dynamically constructing HTML from application data. But you may have noticed that there was an inherent design flaw with my servlet
example—it embeds the HTML code required for the user presentation (UI). RPG programmers haven’t embedded UI code since externally defined files became available (and we say they’re behind the times). That’s where Sun’s JavaServer Pages (JSP) technology enters. JSP effectively separates UI design from business programming logic. In this article, I illustrate how I separated the HTML user interface from the Java code of my servlet example from the August issue using JSP technology.

Before I go into the rewrite of my servlet, I must first lay the groundwork for JSP. JSP is a server-side scripting language; it is parsed on the host to dynamically construct the HTML. HTML scripting languages were initially used on the client (Web browser) to do such things as edit entry fields or selectively use the latest HTML syntax supported by Microsoft Internet Explorer or Netscape Navigator. The scripting language that was first available for HTML was Netscape LiveWire. Netscape soon renamed LiveWire to JavaScript, and Microsoft quickly followed with a clone of JavaScript called JScript. Netscape then had the idea to parse the JavaScript on the host rather than the client so the host could dynamically construct HTML before it was sent to the client. Microsoft followed suit with a much more powerful server-side scripting language called Active Server Pages (ASP). Meanwhile, Sun, doing what it does best, took the best ideas from commonly accepted industry standards and designed JSP technology.

Minimum Standard Requirements

The best way to describe how JSP works is to show you a simple example. The following line of text contains the complete HTML syntax from a file called Minimal.html:

Minimal HTML file

When a Web server receives a request from a browser for Minimal.html, it simply sends that text file down to the browser. But if you rename Minimal.html (on the server machine, that is) to Minimal.jsp, the process works entirely differently: When a browser requests the file called Minimal.jsp, the JSP-enabled server (e.g., AS/400’s HTTP Server for AS/400 and IBM Corporation’s WebSphere) sees the JSP suffix and compiles the JSP file. That’s right; the Web application server compiles the HTML text contained within that file. This page-compile process converts the JSP into the Java servlet source file shown in Figure 1 and compiles that source into a Java class. The Web application server then executes the Java servlet, which simply creates the same HTML shown earlier. The browser receives that HTML and presents “Minimal HTML file” in the browser window.

Obviously, this compile process takes up a considerable amount of time (a few seconds). But the next time a client requests that same JSP file, the server will simply execute the servlet created earlier. Meanwhile, if a Web developer modifies the JSP file, the server will notice that the JSP has been changed, re-create the Java code, and compile a new servlet.

Scriptlets

At this point, I have not shown any value-add of JSP technology, so my next example uses some JSP scripting:


Today’s date <%=(new java.util.Date()).toLocaleString() %>

This simple JSP example contains Java code within the JSP scripting tags of <%= and %>. When this JSP page is requested, the servlet automatically generated by the Web server will dynamically insert today’s date into an HTML file. The dynamically constructed HTML file is sent to the requesting browser and presented to the user in the following format:

Today’s date Sep 8, 1999 8:14:29 PM Any Java syntax can be used in a JSP file. Also, because a JSP file ultimately becomes a Java servlet, the parameters that are sent to the standard functions of a servlet can be used in the JSP. The following example uses the HttpServletRequest object variable called request to retrieve the name of the requesting Web browser:


<%= request.getHeader(“User-Agent”) %>

When I requested the JSP file that contained the above syntax from Internet Explorer, the browser displayed “Mozilla/4.0 (compatible; MSIE 4.0; Windows 95),” but when I requested that same JSP from Netscape Navigator, I saw “Mozilla/4.06 [en] (Win95; U ;Nav).” The HttpServletRequest class provides encapsulated object-oriented access to all the information that could ever possibly be embedded to Web requests such as HTTP cookies, HTTP headers, HTML form input parameters, and HTTP query strings. A few of the methods at your disposal from the HttpServletRequest class are getCookies, getHeader, getParameter, and getQueryString. Three other object variables are also available in the Java code of your JSP file: response, out, and in. The classes of the out and in object variables are from the java.io package (PrintWriter and BufferedReader). The class of the response object variable is HttpServletResponse. It’s sort of the opposite of HttpServletRequest, and as you might guess, the HttpServletResponse class encapsulates object-oriented access to any of the facilities available with an HTTP response that is to be sent back to the client. For instance, HttpServerResponse has functions such as

addCookie, setHeader, and sendRedirect. Through the HttpServletRequest and the HttpServletResponse classes, you will be able to do with ease what CGI programmers must struggle with.

When more than one line of Java code is contained within the <% and %> tags, that section of code is known as a scriptlet. The Java syntax that can be inserted between the <% and %> tags of a JSP file can be as complex as you desire. But you really don’t want to have that much Java code in your JSP. Why? Because you’d then have the opposite problem of embedding HTML code in a Java servlet—you’d have Java code embedded into what is basically an HTML file. Again, the idea with JSP is to separate presentation from programming. There’s a lot more cool stuff that you can do with JSP scriptlets, but I want to move on to a much cleaner strategy of coding your UI with JSP without the use of complex Java code.

Beans, Beans

JavaServer Pages cleanly separate the UI from programming logic with JavaBeans, Sun’s strategy for component-based programming. A JavaBean is basically a Java class that conforms to a standard naming and coding strategy for functions. The intent of JavaBeans is to provide a functional interface that is easy to use. A JavaBean, in fact, should be so easy to use that a Web designer with little or no Java training can use it through a JSP tag called BEAN. The following is the bean tag’s formal syntax:

type=”class_or_interface_name”

introspect=”yes|no” beanName=”ser_filename”

create=”yes|no”

scope=”request|session|userprofile”>

The term bean refers to a JavaBean, and a JavaBean is simply a Java class that conforms to a simple yet standard strategy for coding function interfaces. The JavaBean is where the complex code belongs—not in the JSP file. By using a JavaBean, you cleanly separate the UI from the business logic. To pull out the HTML that I had embedded in my servlet example in “Serving Up Host-based Java Apps,” I created a simple JavaBean that I called SeminarBean.

To understand how the SeminarBean JavaBean fits into my JSP example, you first need to look at its UI. The UI for my example as it appears in Navigator is shown in Figure 2, and the JSP code that generates that page is shown in Figure 3. Notice the BEAN tag at the top of the JSP in Figure 3. It references the SeminarBean JavaBean with the type qualifier. The code for SeminarBean is shown in Figure 4. It’s a trivial example in that its
“dynamic” data doesn’t even come from DB2 for OS/400. For simplicity, I hardcoded the data as compile-time arrays. But the idea is that I’ve encapsulated access to a business entity with some simple Java code. The JSP file of Figure 3 is able to use the functions of that SeminarBean through the variable name of “seminars” that I specified using the name qualifier in the BEAN tag.

Iteration

To construct the HTML list of seminar dates shown in the browser graphic in Figure 2, the JSP repeatedly invokes the SeminarBean’s getDate function. That “iteration” is enabled with JSP’s REPEAT tag. The REPEAT tag lets you specify an index variable that you can then use as a parameter to your JavaBean function calls.

To construct the drop-down list for users to select the city where they wish to attend one of my Java seminars, I again use the REPEAT tag, but this time, I invoke the getCity function of the SeminarBean.

My trivial SeminarBean has no functions available to set its attributes, but if it did, I could easily invoke setter functions to update my seminar database from user input to the HTML form. The form of my JSP, however, is sent for processing to a servlet called Seminar ForJSP, as identified in the ACTION option of the FORM tag:

The Java code for the SeminarForJSP servlet is shown in Figure 5. All the SeminarForJSP servlet does is read the parameter values for name and city, then send the HTML that encapsulates the following note to the registrant:

Registration Confirmation
“Thank you, Don Denoncourt. Your registration is confirmed for San Antonio.”

More Stuff

There are a couple of other capabilities of JSP that I want to mention. First is the ability of a JSP to directly call a servlet with the SERVLET tag. The second capability is that a servlet can call a JSP with the callPage function. In a typical scenario, a standard HTML file presents a form to the user. A servlet is identified with the form tag’s action option to handle the user input. The servlet uses the full potential of the Java programming language, but instead of embedding an HTML response to the user, the servlet creates a JavaBean that encapsulates the information and perhaps encapsulates the ability to manipulate the state of that information. The servlet then calls a JSP with the callPage function. The JSP’s BEAN tag references the JavaBean created in the servlet.

Now, realize that the developer of the servlet is a business programmer and the developer of the JSP is a Web designer. The Web designer is easily able to retrieve information from the JavaBean and then do what she does best with that
information—design a well-crafted Web page. If the Web developer needs additional computing power, she may request that a servlet be developed so she can invoke it from her JSP page with the SERVLET tag. The Web designer can even invoke another JSP from within a JSP, thus allowing the design of a modular Web site. With the intelligent use of JSP, servlets, and JavaBeans, you can easily engineer the separation of presentation and programming.

Find Out More

For documentation, you can download the IBM Redbook Developing an e-business Application for the IBM WebSphere Application Server (SG24-5423-00) from www.redbooks.ibm.com. The “e-biz book,” as I call it, provides a complete example application called Home Bank that uses JSP, servlets, and JavaBeans. Two valuable PDFs that are AS/400-specific are available for download from IBM’s Technical Studio site (www.as400.ibm.com/tstudio/websphere/docs/doc.htm): “WebSphere Application Server for AS/400 Documentation Center” and “Getting Started with WebSphere Application Server for AS/400.” You can also retrieve JSP specifications from Sun’s Web site (www.java.sun.com/products/jsp).

To run JSP from your AS/400, you need the HTTP Server for AS/400 (5769DG1) and WebSphere Application Server for AS/400 (5769AS1) program products installed and configured (both of which are free with V4R3 and V4R4). For information on installing WebSphere to your V4R3 machine, see “WebSphere for AS/400 Setup,” Lisa Wellman, AS/400 NetJava Expert (Web Edition), February/March 1999, www.midrangecomputing. com/anje/99/02. For information on installing WebSphere on your V4R4 machine, see my piece “Pointer: Enabling JSP with V4R4,” AS/400 NetJava Expert (Web Edition), October/, www.midrangecomputing. com/anje. If you don’t have an

AS/400 at OS/400 V4R3 or higher or if you just want to test JSPs on your PC, download Sun’s JavaServer Web Development Kit 1.0 (www.java.sun.com/products/jsp).

Consider Yourself Served

You’ve been served. You have now been presented with notice of the power of JavaServer Pages, so it’s time to get started. My example was necessarily simplistic in order to illustrate the relevant concepts. However, you should still be able to envision the potential for combining JSP, servlets, and JavaBeans to separate the UI from the business logic. This logical separation of tasks supports a collaborative work environment where Web designers can design Web pages and business programmers can code business logic.

REFERENCES

• Developing an e-business Application for the IBM WebSphere Application Server, Redbook (SG24-5423-00)

• Pointer: Enabling JSP with V4R4,” Don Denoncourt, AS/400 NetJava Expert (Web Edition), October/, www.midrangecomputing.com/anje
• ”Serving Up Host-based Java Apps,” Don Denoncourt, MC, August 1999
• ”WebSphere for AS/400 Setup,” Lisa Wellman, AS/400 NetJava Expert (Web Edition), February/March 1999, www.midrangecomputing.com/anje/99/02

package D_0003a.Java.jswdk_0002d_00031_0005f_00030.examples.jsp;
import javax.servlet.*;
// code omitted
public class Minimal_jsp_1 extends HttpJspBase {

static char[][] _jspx_html_data = null;

// code omitted

private static boolean _jspx_inited = false;

public final void _jspx_init() throws JspException {

// code omitted

FileInputStream fin = new FileInputStream(

"work%3A8080%2FexamplesD_0003a.Java.jswdk_"+

"0002d_00031_0005f_00030.examples.jspMinimal.dat");

// code omitted

}

public void _jspService(HttpServletRequest request,

HttpServletResponse response)

throws IOException, ServletException {

JspFactory _jspxFactory = null;

PageContext pageContext = null;

HttpSession session = null;

ServletContext application = null;

ServletConfig config = null;

JspWriter out = null;

Object page = this;

String _value = null;

try {

if (_jspx_inited == false) {

_jspx_init();

_jspx_inited = true;

}

_jspxFactory = JspFactory.getDefaultFactory();

response.setContentType("text/html");

pageContext = _jspxFactory.getPageContext(this,

request, response, "", true, 8192, true);

application = pageContext.getServletContext();

config = pageContext.getServletConfig();

session = pageContext.getSession();

out = pageContext.getOut();

out.print(_jspx_html_data[0]);

} catch (Throwable t) {

// code omitted

}

}

Figure 1: The servlet code automatically generated by the Web application server’s page compile process is ugly.





Reconcilable_Differences06-00.png 600x614

Figure 2: JavaServer Pages are processed on the host to dynamically generate HTML to be sent to Web browsers.

MC Java Seminars

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

Spring '00 Seminar Dates


create="yes" scope="session" introspect="no">

  • <%= seminars.getDate(i) %>



Online Registration



City:
 

Figure 3: The BEAN tag of JSP references a JavaBean so that the JSP file can invoke the functions of that JavaBean.

package Seminar;
import java.util.*;

public class SeminarBean {

String cities[] = {

"Los Angeles", "San Antonio",

"Boston", "Chicago", "Secaucus"};

String[] dates = {

" January 24 to January 28 in Los Angeles",

"February 28 to March 2 in San Antonio",

" March 20 to March 24 in Boston",

" April 10 to April 14 in Chicago",

" April 24 to April 28 in Secaucus"};

public String[] getDates() {return dates;}

public String[] getCities() {return cities;}

public String getDate(int i) {return dates[i];}

public String getCity(int i) {return cities[i];}
}

Figure 4: A JavaBean is a Java class that is coded to follow a simple but standard strategy for coding function interfaces.

public class SeminarForJSP extends HttpServlet
{

public void doPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException

{

resp.setContentType("text/html");

PrintWriter out = new PrintWriter(resp.getOutputStream());

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

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

out.println("Seminar Confirmation");

out.println("");

out.println("

Registration Confirmation

");

out.println("
Thank you, "+name+". "+

"Your registration is confirmed for "+

city+".");

out.println("");

out.close();

}

}

Figure 5: Servlets can embed HTML code as the SeminarForJSP servlet does, or they can delegate that responsibility to a JSP.

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

$0.00 Raised:
$

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: