Its tough enough to learn a new programming language, much less to learn a whole new strategy for deploying applications. Im 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 connectedthus retaining application state between user requestsuntil 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 Pelkies In the HTML Drivers 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 Ive done is confuse you. Ive told you the HTTP architecture is completely different from that of 5250 applications, Ive introduced HTTP and HTML, and Ive suggested you could use any of a variety of languages to handle Web input. Let me simplify everything for you: Just use JSPsthat 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 opensone for reading and one for writingbut 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 objects 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 dont 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 HttpServletRequests getCookies method and the HttpServletResponses 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 servers 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 HttpServletRequests 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 variables 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. Im not going to describe HTTP methods in detail here. Suffice it to say that you can use either GET or POST. Ill 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 fields 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 its 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 objects getParameter method. Then, if a cookie name was indeed set by the user, a cookie object is created. The cookie objects 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 PCs 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 JSPs 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 Suns free JavaServer Web Development Kit (JSWDKavailable 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 Suns 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 IBMs WebSphere (although its 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 Drivers 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 users request parameters
getQueryString: returns a string containing all the users 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 users 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 files response object has the full strength of HTTP through the methods of the HttpServletResponse class.
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.
Figure 4: Much of the information contained within an HTTP packet is standard HTTP headers.
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:
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 objects getCookies method and create cookies with the response objects addCookie method.
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.
LATEST COMMENTS
MC Press Online