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 Suns 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
exampleit embeds the HTML code required for the user presentation (UI). RPG programmers havent embedded UI code since externally defined files became available (and we say theyre behind the times). Thats where Suns 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/400s HTTP Server for AS/400 and IBM Corporations WebSphere) sees the JSP suffix and compiles the JSP file. Thats 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:
Todays 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 todays 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:
Todays 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. Its 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 dont want to have that much Java code in your JSP. Why? Because youd then have the opposite problem of embedding HTML code in a Java servletyoud have Java code embedded into what is basically an HTML file. Again, the idea with JSP is to separate presentation from programming. Theres 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, Suns 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 tags 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 belongsnot 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. Its a trivial example in that its
dynamic data doesnt even come from DB2 for OS/400. For simplicity, I hardcoded the data as compile-time arrays. But the idea is that Ive 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 SeminarBeans getDate function. That iteration is enabled with JSPs 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 tags 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 JSPs 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
informationdesign 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 IBMs 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 Suns 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 dont have an
AS/400 at OS/400 V4R3 or higher or if you just want to test JSPs on your PC, download Suns JavaServer Web Development Kit 1.0 (www.java.sun.com/products/jsp).
Consider Yourself Served
Youve been served. You have now been presented with notice of the power of JavaServer Pages, so its 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 servers page compile process is ugly.
Figure 2: JavaServer Pages are processed on the host to dynamically generate HTML to be sent to Web browsers.
ALIGN="Top" WIDTH=500 HEIGHT=200>
Spring '00 Seminar Dates
create="yes" scope="session" introspect="no">
Online Registration
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("
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.
LATEST COMMENTS
MC Press Online