29
Fri, Nov
0 New Articles

Mastering Web Browser Fundamentals JavaServer Pages with JavaServer Pages

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

It’s tough enough to learn a new programming language, much less to learn a whole new strategy for deploying applications. I’m here to help. When you develop cross-platform Web applications, you need to learn, at a minimum, HTTP, HTML, and Java. Further, Java can be deployed using Java servlets, JavaServer Pages (JSPs), and JavaBeans. A complete application is made up of a mix of HTML files, JSP files, Java servlets, and back-office applications that may be written in either Java or your legacy language of choice. Learning all of these technologies may seem a little daunting to you, so I suggest that, before you go about extending your applications to the Web, you first become comfortable with the architecture of Web applications using JSP.

HTTP: The Protocol of the Web

To understand the Web, you need to become comfortable with the protocol of the Web: HTTP. HTTP is quite different from the application protocol that AS/400 programmers are familiar with: 5250 data streams. The biggest difference between HTTP and 5250 data streams is that HTTP is stateless. When a user sitting in front of a Web client (a browser) clicks a Submit button or keys a URL, the browser connects to the server and the server responds with a Web page and then terminates the connection. The next time the user requests something from the server, which may be only seconds later, the server no longer has the application state (file cursors, data structure values, and so forth) for that user; it has effectively “forgotten” who she was or what she did last. On the other hand, 5250 applications stay connected—thus retaining application state between user requests—until a user signs off. Fortunately, there are several ways around this, one of which I will show you in a bit.

HTML: The New User Interface

While HTTP is supplanting 5250 as the new application protocol, HTML is replacing AS/400 display files as the application user interface. HTML forms have replaced 5250


record formats. The following lines of HTML present an entry form with one input field and a Submit button:

METHOD=”GET”>
Prompt:

When the user clicks the Submit button (a.k.a. generating a request), the program name qualified in the ACTION option of the

...
tags is invoked on the server. That host program then dynamically constructs HTML in response to the user request. (For more information on HTML forms, see Teresa Pelkie’s “In the HTML Driver’s Seat” in the December 1999 issue of MC.) The host program can be coded in almost any language, such as RPG, Java, Visual Basic (on NT/2000), or Net.Data.

JSPs Do HTTP

So far, perhaps all I’ve done is confuse you. I’ve told you the HTTP architecture is completely different from that of 5250 applications, I’ve introduced HTTP and HTML, and I’ve suggested you could use any of a variety of languages to handle Web input. Let me simplify everything for you: Just use JSPs—that is, until you are comfortable with the architecture of the Web. Use JSPs to learn the Web and a bit of Java syntax, then start to use a full suite of Internet technologies such as Java servlets, Extensible Markup Language (XML), Enterprise JavaBeans (EJBs), Cascading Style Sheets (CSS), and JavaScript as you become more comfortable with the environment.

As I covered last month in “Bridge the Java Gap with JSP” (MC, May 2000), JSPs combine the syntax of HTML and Java into one source file. A JSP file is really HTML with embedded Java. The Java code is placed between sets of <% and %> tags, and anything outside those JSP tags is standard HTML.

The first step to learning the Web is understanding the flow of information between the Web client (the browser) and the Web host (the HTTP server). Normally, the host application needs to decipher the browser-based user request (generated when the user clicks the Submit button or navigates to a particular URL) and then respond with an HTTP response that contains embedded HTML (to display the results of the request). JSPs make that process easy because all JSP files automatically have two powerful variables, request and response, that provide simplified access to these HTTP functions. You could compare these two object variables as display file opens—one for reading and one for writing—but that would understate their object-oriented power. The data types of the request and response variables are the two Java classes HttpServletRequest and HttpServletResponse. Figure 1 and Figure 2 list some of the more powerful methods of the HttpServletRequest and HttpServletResponse classes.

You can learn a lot about HTTP by writing a JSP that simply invokes the various methods of the HttpServletRequest and HttpServletResponse objects. As shown in Figure 3 (see Figure 4 for the results) under the

header “HttpServletRequest methods,” the JSP example invokes the HttpServletRequest object’s getMethod with the following statement:

<%= request.getMethod()%>

Notice the use of the special equal sign (=) just after <%. The equal sign tells the Web server to embed the results of execution of the enclosed Java syntax into the HTTP response (which will later automatically be sent back to the Web-browsing user). The example also invokes the getRemoteAddr, getProtocol, and getServerName methods in the same manner. As shown under the

header List of HTTP Headers, the JSP then loops


through and lists all the HTTP headers. Note that each packet of HTTP data that goes across the Internet from a browser to a server contains multiple HTTP headers. Although you don’t usually see them when surfing the Web, HTTP headers are used to further describe the information contained within the HTTP packet (such as Expires, User-Agent, Last-Modified, Location, Referrer, and Set-Cookie). Figure 4 shows the results I received in Netscape Navigator when I requested the JSP file shown in Figure 3.

Finding the Cookie Jar

As I mentioned earlier, the Web is stateless. One strategy that is typically used to “fake” a maintain-state application session is to use HTTP cookies. Cookies is just a cute name for information that is stored in text form on client machines. Cookies work like this: Just before your browser sends a request to a server, it checks to see if there are any nonexpired cookies that have a domain name qualifier that matches the domain name of the current HTTP request; any cookies with a domain name match are automatically added to the HTTP packet in a Set-Cookie HTTP header.

Your server application can store whatever it would like in the cookies repository of its Web browsing clients. Examples range from a number that uniquely identifies the user to application data. Often, server applications put a unique key in a cookie and then use that key to access application state data from a database file. That state data would include such things as the key values for database files and other information that the user last entered or accessed. This approach is superior to polluting the cookie repository of Web browsers with application data. One other example of information often kept in a cookie is user profile and password. The password sounds like a security infraction but usually is only used to retrieve demographic and user configuration information that is stored on the server.

Because HTTP cookies are embedded in HTTP packets, your JSP can retrieve and set HTTP cookies easily using the HttpServletRequest’s getCookies method and the HttpServletResponse’s addCookie method. Figure 5 shows the JSP source that produced the Web page shown in Figure 6. The code lists all the cookies that existed on the client with that server’s domain name and then presents an input form so the user can make his own cookies.

The JSP code in Figure 5 is in three sections: List Cookies, Cookie Input, and Process Cookies Input. The first section, under the

header List of Cookies, spins through an array of cookie objects retrieved from the HttpServletRequest’s getCookies method. Note that the JSP for loop uses another special variable, called out, to add the cookie name and value to the HTTP response. The out object variable, like request and response, is always available for use in your JSP files. The out variable’s data type is JspWriter; it is essentially a handle to the output stream for page content. The typical use for the out JspWriter object is to invoke its println method to add dynamic information to the HTML response.

Making Your Own Cookies

The second section of code in Figure 5 is the Cookie Input form. The Action option of the HTML FORM tag specifies the very same JSP that presents the form MasterTheWebCookies.jsp. The next form tag option is called Method. I’m not going to describe HTTP methods in detail here. Suffice it to say that you can use either GET or POST. I’ll just stick with GET for now. The form has two input fields: newCookie and value. The Type option identifies the input as alphanumeric, and the Name option qualifies the variable name that the host application will later use to retrieve the input field’s value. The Size option is used to set the length of the input area to be presented in the browser. There is a third HTML input statement, but it’s just a standard Submit button. When the user clicks the Submit button, all the input values on the page are sent to the host and the


program associated with the form in its “action” attribute will be invoked by the Web server. Figure 6 shows the input form in Netscape Navigator.

When the user clicks the Add Cookie button, the strings entered for the newCookie and value fields are sent to the MasterTheWebCookies.jsp file for processing. In the first section of code, the JSP lists any existing cookies. Then, in the second section of code, the JSP stuffs the HTML input form into the HTTP response. Finally, in the third section of code, the JSP retrieves the input values with the HttpServletRequest object’s getParameter method. Then, if a cookie name was indeed set by the user, a cookie object is created. The cookie object’s expiration date is set to 30 days from when it was created, and the cookie is stuffed into the HTTP response object. At this point, the JSP has completed processing, and the Web server automatically sends the dynamically constructed HTTP response back to the browser. The browser then adds the cookie to its text-based cookies repository (the actual location of which varies depending upon the browser). Figure 7 shows the contents of my PC’s Netscape Navigator cookies.txt file after I added cookies for my profile and my not-so-secret password.

Become a Web Chef

I suggest that you become comfortable with the architecture of the Web by writing a few JavaServer Pages of your own. Investigate how the Web works through the HTTP methods of a JSP’s request and response objects. Write a mini-application that uses multiple input forms and maintains state using cookies. You can set up a test environment on your PC using Sun’s free JavaServer Web Development Kit (JSWDK—available 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.” Another “free” product you can use not only to test JSPs but also for real-world deployment is IBM’s WebSphere (although it’s only free for the AS/400). Because of their simplicity and power, JSPs are quickly becoming the preferred way to develop cross- platform Web pages.

References and Related Materials

• “Bridge Gap to Java with JSP,” Don Denoncourt, MC, May 2000
• “In the HTML Driver’s Seat,” Teresa Pelkie, MC, December 1999


getCookies: returns an array of Cookie objects sent from the browser.
getHeader: returns the value of HTTP headers. getRemoteUser: Returns user name, if the user has logged in using

HTTP authentication. getRequestURI: Returns the request URL without the request parameters.
getContentLength: returns the total length of the user’s request parameters
getQueryString: returns a string containing all the user’s request parameters.
getMethod: returns the HTTP request type, typically either a

GET or a POST. getHeaderNames: returns an array of all the HTTP headers included in the request.
getRemoteAddr: returns the IP address from the Web browsing user. getSession: returns a handle to a special object variable that maintains application state for a user getContentType: returns the type of content sent from the user. getParameter: returns the value of a specific request parameter.

Figure 1: The HttpServletRequest object makes it easy to manipulate HTTP data. These are its methods.


addCookie: adds textual data in the HTTP request, which the user’s browser will subsequently add to its cookies repository.
encodeURL: stuffs the session id in the response URL. setHeader: adds an HTTP response header with a given name and values.
getCharacterEncoding: Returns the name of the character set used for the MIME body sent by this response. setContentLength: Sets the length of the content the server returns to the client.
encodeRedirectURL: Encodes the specified URL for use in the sendRedirect method.
sendError: Sends an error response to the client using the specified status code and a default message. setStatus: Sets the status code for the HTTP response. getOutputStream: Returns a handle to a data stream that can be used to write binary response data. setContentType: Sets the content type of the response the server sends to the client e.g. text/html.

Figure 2: A JSP file’s response object has the full strength of HTTP through the methods of the HttpServletResponse class.

Master the Web with Java Server Pages

Accessing HTTP Information

HttpServletRequest methods:


getMethod:  
<%= request.getMethod()%>

getRemoteAddr:  
<%= request.getRemoteAddr()%>

getProtocol:  
<%= request.getProtocol()%>

getServerName:  
<%= request.getServerName()%>

List of HTTP Headers:


<%

java.util.Enumeration headers =

request.getHeaderNames();

for (int i = 0; headers.hasMoreElements(); i++)

{

String header = (String)headers.nextElement();

out.println(header+”: “);

out.println(request.getHeader(header)+”
”);

}

%>

Figure 3: You can decipher HTTP information simply by invoking the methods of the request and response objects.


Mastering_Web_Browser_Fundamentals_JavaServer_Pages_with...07-00.png 394x293

Figure 4: Much of the information contained within an HTTP packet is standard HTTP headers.

Master the Web with Java Server Pages

Cookies for Everyone

<%-- List Cookies --%>

List of Cookies:


<%

Cookie[] cookies = request.getCookies();

for (int i = 0; i < cookies.length; i++)

{

out.println(cookies[i].getName()+”: “);

out.println(cookies[i].getValue()+”
”);

}

%>

<%-- Cookie Input --%>

Make your own cookie:



Name for new cookie:  

Value:  



<%-- Process Cookies Input --%>
<%

String cookieName = request.getParameter(“newCookie”);

String cookieValue = request.getParameter(“value”);

if (cookieName != null) {

Cookie cookie = new Cookie(cookieName, cookieValue);

final int expireDays = 30;

cookie.setMaxAge(expireDays*24*60*60);

response.addCookie(cookie);

}

%>

Figure 5: You can retrieve cookies with the request object’s getCookies method and create cookies with the response object’s addCookie method.


Mastering_Web_Browser_Fundamentals_JavaServer_Pages_with...08-00.png 405x245

Figure 6: Web applications often use HTTP cookies to maintain state between user requests.

# Netscape HTTP Cookie File

# http://www.netscape.com/newsref/std/cookie_spec.html

# This is a generated file! Do not edit.

127.0.0.1:8080 FALSE /examples FALSE 957366725 profile denoncourt

127.0.0.1:8080 FALSE /examples FALSE 957366734 password secret

Figure 7: HTTP cookies are benign: You cannot load a virus with a cookie, as it is always text-based.


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: