HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML
 

Separating presentation and logic when building server-side Web-based applications allows you to generate Web pages with dynamic content easier and faster. It also enables Web designers who aren't especially experienced in application development to easily change the appearance of a Web page. For Web sites with information content that needs to change frequently, this advantage means that the update cycle can occur much more rapidly...thus bringing new information to Web site visitors faster.

Early Web-based applications were simple and usually contained both presentation and business logic, which created maintenance problems when changes occurred to either. Separating the two simplifies maintenance and allows faster and easier updates. This article will discuss two underlying technologies that can be used for presentation and logic separation: Java Servlets and JavaServer Pages (JSP). A simple application architecture in the context of a small demonstration will show you how to achieve this separation and deploy and change Web applications faster.

As the first step let me give a brief overview of Java Servlets and JSP - and of how they work together in a Web application architecture.

What's a Servlet?
Servlets are platform-independent 100% Pure Java server-side modules that fit seamlessly into the framework of an application server. They can be used to extend the capabilities of the server in a variety of ways with minimal overhead, maintenance and support. Because servlets are Java bytecode that can be downloaded or shipped across the network, they are truly "Write Once, Run Anywhere." Unlike CGI scripts, servlets involve no platform-specific consideration or modifications: they're Java application components that are downloaded, on demand, to the part of the system that needs them.

What's a JavaServer Page?
JSP is the Java platform technology for building applications containing dynamic Web content such as HTML, DHTML or XML. A JSP page is a text-based document containing static HTML and dynamic actions that describe how to process a response to the client. At development time, JSPs are very different from servlets. However, they are precompiled into servlets at runtime and executed by a JSP engine ,which is installed on a Web-enabled application server such as WebSphere V3.0.

Servlets and JSP Working Together
It's possible for a servlet to take an HTTP request from a Web browser, generate the request dynamically (possibly querying back-end systems to fulfill the request) and then send a response containing an HTML or XML document to the browser.

The drawback of this approach is that the creation of the page must be handled in the Java Servlet, which means that if Web page designers wanted to change the appearance of the page, they'd have to edit and recompile the servlet. With this approach, generating pages with dynamic content still requires some application development experience. Clearly the servlet request-handling logic needs to be separated from the page presentation.

The solution is to adopt the Model-View-Controller (MVC) paradigm for building user interfaces. With MVC, the back-end system is your Model, the templates for creating the look and feel of the response is the View and the code that glues it all together is the Controller. JSPs fit perfectly into this solution as a way of creating a dynamic response or View. Servlets containing logic for managing requests act as the Controller, while your existing business rules are the Model.

Let's look at a small demo application that utilizes the proposed MVC paradigm for presentation and logic separation. The demo provides browser-based access to a 3270 back-end system.

The architecture of the demo application follows the MVC design (see Figure 1).

Figure 1
Figure 1:

A browser using HTML and JSP pages provides the View. A set of Java Servlets and JSPs in an application server provide the Control, while the backend CICS or PeerLogic applications provide the business rules or the Model. The flow between these servlets, HTML and JSP pages is shown in Figure 2 and described in the text that follows. (The source code for the Login Servlet and Login JSP files can be found on the JDJ Web site at www.javadevelopersjournal.com.)

Figure 2
Figure 2:


Demo Application Flow Explained
The Request
The user will typically start with a page of HTML running within a browser. This page will be served from a Web-enabled application server. The application server serves files the same way a standard Web server such as Apache does. This page is an entry point into the Web application. It uses the HTML FORM tag to access the servlet, in our case, LoginServlet. Additional parameters can also be sent to the servlet within the bounds of the FORM action. An example of this would be as follows:

<FORM action="http://localhost:8080/servlet/LoginServlet" method="GET">
<input type="text" size="30" name="firstname">
<input type="text" size="30" name="surname">
.
.
<input type=hidden name=host value="localhost">
<input type=hidden name=port value="9876">
<input type=submit value=" Submit ">
</FORM>

The request will most likely be made using the HTTP or securely using HTTPS. This incoming request is then handled by the servlet, which uses the HttpServletRequest, getParameter() method to gain access to the FORM variables (see Listing 1).

The servlet then tests to see if the user has a session. A session is used to associate a set of unique requests from a remote client; this is necessary due to the stateless nature of the HTTP protocol.

A session is created as follows:

HttpSession session = req.getSession(true);

Objects can then be added to the session:

session.putValue("host", hostToConnectTo);
session.putValue("port", tmpPort);
}
}

The Controller
Servlets are responsible for invoking JavaBeans, which process the user's request. They are also responsible for creating the response to the user. In this proposed architecture it is done by passing the response to a JavaServer Page. For this reason (in object-oriented terms) the servlet is referred to as the controller.

Back to our example. The following code instantiates a new class of the type CICSEmulator called newEmulator. This is a vendor-supplied class from PeerLogic, Inc. CICSEmulator is a 3270 terminal emulator that exposes a set of methods for direct emulator manipulation. The newEmulator can be passed variables from the session, and in this case connected to the host and port of the remote system.

CICSEmulator newEmulator = new CICSEmulator();
newEmulator.setTN3270Port(portToConnectTo);
newEmulator.setTN3270Host(hostToConnectTo);

The second class instantiated is a JavaBean called AcctDetails. This bean was created using the LiveContent PATH 3270 tool from PeerLogic, Inc. AcctDetails is a data access bean; it performs the actual navigation and data retrieval from the back-end 3270 system. AcctDetails assigns the newEmulator class to be its 3270 terminal, then passes the input variables, surname and firstname to its set methods.

AcctDetails getAccountDetails = new AcctDetails();
getAccountDetails.set3270Emulator(newEmulator);

getAccountDetails.setSurname(inputsurname);
getAccountDetails.setFirstName(inputfirstname);

Executing the Request Using the Data Access Beans
The performWork() method of the instantiated bean, getAccountDetails, connects to the back-end 3270 system and retrieves the account details based on the surname and firstname that the user supplied:
try {
getAccountDetails.performWork();
session.putValue("resultsBean", getAccountDetails);
}

catch ( IllegalStateException e ) {
// handle the error
}

If successful, the servlet places the getAccountDetails bean into the user's session. This bean is given an identifier of resultsBean, as it now contains the results of the user's query. These results are then accessible through the bean's get methods.

Passing Control to the JSP
As mentioned, an important part of the Model-View-Controller approach is that presentation be kept separate from business logic. As you've seen, the servlet is responsible for processing the request using the data access beans. The data access bean, getAccountDetails, contains server-side logic for accessing and retrieving data from the back-end system. The back-end system itself (or the Model), contains all of the business rules. The response (or View) the user sees is created using JSP technology. JSPs are dynamic HTML pages containing small pieces of embedded Java code.

The servlet passes both the request and response objects to the JSP using the following syntax:

getServletContext().getRequestDispatcher("/jspDemo/login.jsp").forward(req, res);

The forward method allows the servlet to pass the processing of the response to another resource. Its request and response parameters must be the same objects that were passed to the calling servlet's service method.

It uses the RequestDispatcher object obtained via getRequestDispatcher() to determine the path to the JSP target resource. The pathname to the JSP must begin with a "/" and is interpreted as relative to the current context root.

Accessing the Results Bean
The JSP is responsible for creating the response for the user, which it does by gaining access to the getAccountDetails bean data (referred to by the resultsBean ID). This is done using the following syntax within the HTML page:

<HTML>
<BODY>
.
.
<jsp:useBean id="resultsBean" scope="session" class="acct.AcctDetails " />
<jsp:setProperty name="resultsBean" property="*"/>

The <jsp:useBean> action tries to find an existing object (in this case the resultsBean) using the ID and scope. In our example, we placed the getAccountDetails bean into the session and named it resultsBean. The action will therefore get the resultsBean from the user's session. Once this is done, the JSP can access any of the resultBean's get methods that gain access to its data. This is done using the following JSP syntax:

<%= resultsBean.getDetails_Title() %>
<%= resultsBean.getDetails_Initial() %>

This syntax is an example of a JSP expression. Anything between the <%= and %> markers is evaluated by the JSP engine, with the results sent as output to the JSP file. The two expressions above will execute the ResultsBean get methods for displaying the user's title and middle initial - exciting stuff! JSP code can be embedded throughout an HTML page the same way a scripting language such as JavaScript would. JSP syntax is relatively simple to understand. This means that the JSPs can be maintained by Web page designers rather than by the application programmers, who are responsible for the servlets and data access beans. Changes can be made to a JSP without affecting the servlet and vice versa.

The Response
The JSP is dynamically compiled into a Java Servlet at request time and cached by the application server. The advantage of this is that any subsequent request will be extremely quick. The response the user receives is basically an HTML page (with a .jsp extension) that contains dynamically generated content.

Summary
In the demo architecture I've described in this article, the client makes a request from a Web browser directly to a servlet, which then processes the request by using data access JavaBeans to retrieve data from the backend system. The servlet wraps the results into a results bean, places it into the session, then invokes a JSP to handle the response. The servlet is in complete control of the initiated request up to the time the response is generated.

It's up to the called JSP to generate the content needed for the response to the user. The JSP should include only logic that's needed for formatting the presentation. The advantage of this type of separation is that it creates more reusable, portable platform-independent components that can be shared between applications and implemented as part of a larger application.

Separating the actual development of the servlet logic and JSP presentation means that Web page designers and application developers can work independently of each other. This development approach conforms to the MVC paradigm that was outlined in the beginning of this document.

Author Bio
Barry Tait, an experienced Java developer, is the Web architect for PeerLogic, Inc., a company offering software that facilitates Java access to legacy mainframe applications and simplifies mainframe data access. He specializes in Web architecture. Before working with Java, Barry worked on CICS development for IBM. [email protected]

	

Listing 1 : 
  
public class LoginServlet extends HttpServlet { 

 public void doGet (HttpServletRequest req, HttpServletResponse res) 
      throws ServletException, IOException 

{ 
String   inputsurname = req.getParameter("surname"); 
String   inputfirstname = req.getParameter("firstname"); 
String  hostToConnectTo = req.getParameter("host"); 
String  tmpPort = req.getParameter("port"); 
int  portToConnectTo = Integer.valueOf(tmpPort).intValue();  . 
. 
  
  
  
  

Appendix A  Sample Demo Code 

Servlet Code Example - LoginServlet.java 

/* 
 * LoginServlet.java  7/27/99 
 * Barry Tait 
 * 
 * Processes the client request by logging into Accounting application - ACCT 
 * and retrieving client infomation. ACCT takes a surname and firstname as input 
 * from the client. 
 * 
 * It then logs into a Stockbroking application - DMOI, using the account 
 * number retrieved from ACCT. It retrieves portfolio details from DMOI then 
 * calls a JavaServer Page (JSP) which creates the response. 
 * 
 */ 

import java.io.*; 
import java.util.Vector; 
import javax.servlet.*; 
import javax.servlet.http.*; 
import peerlogic.clientapis.emulator.*; 
import acct.*; 
import dmoi.*; 

public class LoginServlet extends HttpServlet { 

    public void doGet (HttpServletRequest req, HttpServletResponse res) 
      throws ServletException, IOException 

    { 
 String  inputsurname = req.getParameter("surname"); 
 String  inputfirstname = req.getParameter("firstname"); 
 String hostToConnectTo = req.getParameter("host"); 
 String tmpPort = req.getParameter("port"); 
 int portToConnectTo = Integer.valueOf(tmpPort).intValue(); 

 // 
 // Create session object 
 // 
 HttpSession session = req.getSession(true); 

 // 
 // Put variables into session 
 // 
 session.putValue("host", hostToConnectTo); 
 session.putValue("port", tmpPort); 

 // 
 // Instantiate New PeerLogic PATH3270 Beans 
 // 
 KixEmulator newEmulator = new KixEmulator(); 
 KixEmulator newEmulator2 = new KixEmulator(); 
   AcctDetails getAccountDetails = new AcctDetails(); 
 DmoiLogin getDmoiDetails = new DmoiLogin(); 

 newEmulator.setTN3270Port(portToConnectTo); 
   newEmulator.setTN3270Host(hostToConnectTo); 
 newEmulator2.setTN3270Port(portToConnectTo); 
   newEmulator2.setTN3270Host(hostToConnectTo); 

// 
 // Assign terminal Bean to each data access Bean 
 // 
 getAccountDetails.setKixEmulator(newEmulator); 
 getDmoiDetails.setKixEmulator(newEmulator2); 
 // 
 // Set variables from form 
 // 
 getAccountDetails.setSurname(inputsurname); 
 getAccountDetails.setFirstName(inputfirstname); 

  // 
 // Login to system and execute the "acct" transaction. 
 // As input enter a surname and firstname. Capture details if user 
 // exists and display JSP. If there's an error display loginError.jsp. 
 // 
  
 try { 
  getAccountDetails.performWork(); 

  // 
  // Put AcctDetails bean - getAccountDetails, into session so 
// that the JSP can access it. This bean will contain the retrieved client 
// information from the accounting application - ACCT. 
  // 
  session.putValue("resultsBean", getAccountDetails); 

  // 
// Get Account No. (acctID) from getAccountDetails Bean - this is used to 
// drive the DmoiLogin Bean - getDmoiDetails 
  // 
  String acctID = getAccountDetails.getDetails_acctID(); 

  // 
  // Use the acctID for login to the DMOI application 
  // 
  getDmoiDetails.setUserID(acctID); 

  // 
  // Login to DMOI and add the portfolio details to the session 
  // 

         try { 
          getDmoiDetails.performWork(); 

   // 
   // Put getDmoiDetails Bean into session 
   // 
   session.putValue("dmoiResultsBean", getDmoiDetails); 
  
         } 

         catch ( IllegalStateException e ) { 
  
         } 
  

  // 
    // Call the JSP - login.jsp for display 
  // 
  getServletContext().getRequestDispatcher("/jspDemo/login.jsp").forward 
  (req, res); 

 } 

 catch ( IllegalStateException e ) { 
  
// 
  // Call JSP error page if user details are not found 
  // 
getServletContext().getRequestDispatcher("/jspDemo/loginError.jsp"). 
forward(req, res); 
 } 
  
  } 
} 

 JSP Code Example - Login.jsp 

<HTML> 
<HEAD> 
<TITLE>UT Screen Bean Servlet/JSP test page</TITLE> 

<!- Include the JavaScript files needed for client-side validation --> 
<%@ include file="/javascript/checkBuyFields.js" %> 
<%@ include file="/javascript/checkSellFields.js" %> 

</HEAD> 
<BODY> 
<P><font size=1 face="verdana, arial" color=red>
 Display Page:</font>  
<font size=1 face="verdana, arial">Type=JSP name=login.jsp</font> 
</P> 

<!- Import Java Vector class  needed for formatting of table --> 
<%@ page import="java.util.Vector" %> 

<!-- Retrieve Beans from session --> 
<jsp:useBean id="resultsBean" scope="session" class="acct.AcctDetails" /> 
<jsp:setProperty name="resultsBean" property="*"/> 
<jsp:useBean id="dmoiResultsBean" scope="session" class="dmoi.DmoiLogin" /> 
<jsp:setProperty name="dmoiResultsBean" property="*"/> 

<CENTER> 

<!-- Main HTML body --> 
<TABLE WIDTH=670 BORDER=0 CELLPADDING=4 CELLSPACING=4> 
<TR> 
<TD WIDTH=400 ALIGN=left VALIGN=top> 

<P> 
<font size=2 face=verdana> 
<B>Account Details: 
<font color=red> 

<!-- Retrieve data from Bean methods --> 
<%= resultsBean.getDetails_Title() %> 
<%= resultsBean.getDetails_FirstName() %> 
<%= resultsBean.getDetails_Initial() %> 
<%= resultsBean.getDetails_Surname()%> 
</font></B> 
</font> 
</P> 
<BR> 

<!-- Acct details table --> 
<TABLE WIDTH=400 BORDER=1 CELLPADDING=4 CELLSPACING=2> 
<TR> 
<TD BGCOLOR="#eeeeee" WIDTH=120 ALIGN=left> 
<font face="verdana, arial" size=2><b>Account No.:</b></font></TD> 
<TD WIDTH=280 ALIGN=left><font face="verdana, arial" size=2> 
<%= resultsBean.getDetails_acctID() %> 
</font></TD></TR> 

<TR><TD BGCOLOR="#eeeeee" WIDTH=120 ALIGN=left> 
<font face="verdana, arial" size=2><b>Address:</b></font></TD> 
<TD WIDTH=280 ALIGN=left><font face="verdana, arial" size=2> 
<%= resultsBean.getDetails_Address() %> 
</font></TD></TR> 

<TR><TD BGCOLOR="#eeeeee" WIDTH=120 ALIGN=left> 
<font face="verdana, arial" size=2><b>Account Limit:</b></font></TD> 
<TD WIDTH=280 ALIGN=left><font face="verdana, arial" size=2> 
<%= resultsBean.getDetails_Limit() %> 
</font></TD></TR> 
</TABLE> 

<BR> 
<BR> 

<P><font size=2 face=verdana><B>Current Portfolio:<font color=red> 
$ <% if (dmoiResultsBean.getTotalValue() != null) { %> 
  <%= dmoiResultsBean.getTotalValue() %> 
   </font></B></font></P> 
  
   <TABLE WIDTH=400 BORDER=1 CELLPADDING=4 CELLSPACING=2> 
   <TR> 
 <TD BGCOLOR="#eeeeee" WIDTH=100 ALIGN=center> 
 <font face="verdana, arial" size=2><b>Stock</b></font></TD> 
 <TD BGCOLOR="#eeeeee" WIDTH=100 ALIGN=center> 
 <font face="verdana, arial" size=2><b>Volume</b></font></TD> 
 <TD BGCOLOR="#eeeeee" WIDTH=100 ALIGN=center> 
 <font face="verdana, arial" size=2><b>Price</b></font></TD> 
 <TD BGCOLOR="#eeeeee" WIDTH=100 ALIGN=center> 
 <font face="verdana, arial" size=2><b>Total</b></font></TD> 
   </TR> 
  
   <% 
   Vector stocks = dmoiResultsBean.getV_stock(); 
   Vector holdings = dmoiResultsBean.getV_holding(); 
   Vector prices = dmoiResultsBean.getV_price(); 
   Vector values = dmoiResultsBean.getV_value(); 

   for (int i = 0; i < stocks.size(); i++) { %> 
  
    <!-- Test for end of array --> 
  
    <% if (((String)stocks.elementAt(i)).substring(0,1).equals(" ")) {%> 
  <TR> 
 <TD WIDTH=100 ALIGN=center> 
 <% String stockName = ((String)stocks.elementAt(i)); %> 
<font face="verdana, arial" size=2><%= stockName %></font></TD> 
 <TD WIDTH=100 ALIGN=center> 
 <% String holdingAmount = ((String)holdings.elementAt(i)); %> 
 <font face="verdana, arial" size=2><%= holdingAmount %></font></TD> 
 <TD WIDTH=100 ALIGN=center> 
 <% String priceAmount = ((String)prices.elementAt(i)); %> 
 <font face="verdana, arial" size=2><%= priceAmount %></font></TD> 
 <TD WIDTH=100 ALIGN=center> 
 <% String valueAmount = ((String)values.elementAt(i)); %> 
 <font face="verdana, arial" size=2><%= valueAmount %></font></TD> 
 </TR> 
   <% } %> 
  <% } %> 
  </TABLE> 

<% } 

else { 
 out.println("0"); 
} %> 

</TD> 
<TD WIDTH=90> </TD> 

<!-- Buy and Sell Tables --> 
<TD WIDTH=180 ALIGN=center VALIGN=top> 
<P><font size=2 face="verdana">
<B>Transaction Options:</B></font></P> 

<TABLE WIDTH=180 BORDER=1 CELLPADDING=2 CELLSPACING=2><TR> 
<TD BGCOLOR=black ALIGN=center> 
<font face="verdana, arial" size=2 color=white>
<b>Buy Stock</b></font></TD></TR> 
<TR><TD ALIGN=center> 
<FORM Action="/servlet/BuyServlet" 
onSubmit="return checkBuyFields(this)" METHOD=GET> 
<font face="verdana, arial" size=2> 
<SELECT NAME="buyStock" SIZE="1"> 
<OPTION Value="" SELECTED>Please Select</OPTION> 
<OPTION Value=stock1 SELECTED>Stock 1</OPTION> 
<OPTION Value=stock2 SELECTED>Stock 2</OPTION> 
<OPTION Value=stock3 SELECTED>Stock 3</OPTION> 
<OPTION Value=stock4 SELECTED>Stock 4</OPTION> 
<OPTION Value=stock5 SELECTED>Stock 5</OPTION> 
<OPTION Value=stock6 SELECTED>Stock 6</OPTION> 
<OPTION Value=stock7 SELECTED>Stock 7</OPTION> 
<OPTION Value=stock8 SELECTED>Stock 8</OPTION> 
<OPTION Value=stock9 SELECTED>Stock 9</OPTION> 
</SELECT> 
</font> 
</TD></TR> 
<TR><TD ALIGN=center> 
<font face="verdana, arial" size=2>Volume:</font> 
<INPUT NAME="buyVolume" SIZE="5"></TD></TR> 
<TR><TD BGCOLOR="#eeeeee" ALIGN="center">
<INPUT Type="submit" Value="  Submit  "> 
</TD></TR></TABLE> 
</FORM> 

<BR> 

<TABLE WIDTH=180 BORDER=1 CELLPADDING=2 CELLSPACING=2><TR> 
<TD BGCOLOR=black ALIGN=center> 
<font face="verdana, arial" size=2 color=white>
<b>Sell Stock</b></font></TD></TR> 
<TR><TD ALIGN=center> 
<FORM Action="/servlet/SellServlet" 
onSubmit="return checkSellFields(this)" METHOD=GET> 
<font face="verdana, arial" size=2> 
<SELECT NAME="sellStock" SIZE="1"> 
<OPTION Value="" SELECTED>Please Select</OPTION> 
<OPTION Value=stock1 SELECTED>Stock 1</OPTION> 
<OPTION Value=stock2 SELECTED>Stock 2</OPTION> 
<OPTION Value=stock3 SELECTED>Stock 3</OPTION> 
<OPTION Value=stock4 SELECTED>Stock 4</OPTION> 
<OPTION Value=stock5 SELECTED>Stock 5</OPTION> 
<OPTION Value=stock6 SELECTED>Stock 6</OPTION> 
<OPTION Value=stock7 SELECTED>Stock 7</OPTION> 
<OPTION Value=stock8 SELECTED>Stock 8</OPTION> 
<OPTION Value=stock9 SELECTED>Stock 9</OPTION> 
</SELECT> 
</font> 
</TD></TR> 
<TR><TD ALIGN=center> 
<font face="verdana, arial" size=2>Volume:</font> 
<INPUT NAME="sellVolume" SIZE="5"></TD></TR> 
</TD></TR> 
<TR><TD BGCOLOR="#eeeeee" ALIGN=center>
<INPUT Type="submit" Value="  Submit  "> 
</TD> 
</TR> 
</TABLE> 
</FORM> 
<BR> 

<!-- close main table --> 
</TD> 
</TR> 
</TABLE> 
<P ALIGN=center> 
<FORM Action="/servlet/LogoffServlet" METHOD=GET> 
<INPUT Type="hidden" name="logoff" value="true"> 
<INPUT Type="submit" Value="     Click here to Logoff    "> 
</FORM> 
</P> 
</CENTER> 
</BODY> 
</HTML> 
  
  
 
 

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.