Chapter 3
Chapter 5
Chapter 7
Chapter 8
Chapter 9
Download All Code
Home
 
Chapter 5 Examples

Download the Chapter 5 code

View the code examples
5.1   5.2   5.3   5.4   5.5   5.6
5.7   5.8   5.9   5.10   5.11


Example 5.1 Introduce a Controller - JSP Structure

<HTML>
<BODY>
  <control:grant_access/>
.
.
.

</BODY>
  </HTML>

Example 5.2 Introduce a Controller - Controller Structure

if (grantAccess())
{
    dispatchToNextView();
}
else
{
    dispatchToAccessDeniedView();
}

Example 5.3 Generate and Store Token

/**
* Save a new transaction token in the
* user's current session, creating
* a new session if necessary.
*
* @param request The servlet request we are processing
*/
protected void saveToken(HttpServletRequest request) {

HttpSession session = request.getSession();
String token = generateToken(request);
if (token != null)
  session.setAttribute(TRANSACTION_TOKEN_KEY, token);
}

(Copyright (c) 1999 The Apache Software Foundation. All rights 
reserved.)

Example 5.4 Check For a Valid Token

/**
* Return <code>true</code> if there is a transaction 
* token stored in the user's current session, and 
* the value submitted as a request request parameter 
* with this action matches it. 
* 
* Returns <code>false</code>
* under any of the following circumstances:
* <ul>
* <li>No session associated with this request</li>
* <li>No transaction token saved in the session</li>
* <li>No transaction token included as a request 
* parameter</li>
* <li>The included transaction token value does not
*     match the transaction token in the user's
*     session</li>
* </ul>
*
* @param request The servlet request we are processing
*/

protected boolean isTokenValid(HttpServletRequest request) {

    // Retrieve the saved transaction token from our
    // session
    HttpSession session = request.getSession(false);
    if (session == null)
        return (false);
    String saved = (String) 
        session.getAttribute(TRANSACTION_TOKEN_KEY);
    if (saved == null)
        return (false);
    // Retrieve the transaction token included in this
    // request
    String token = (String) 
        request.getParameter(Constants.TOKEN_KEY);
    if (token == null)
        return (false);

    // Do the values match?
    return (saved.equals(token));

}
(Copyright (c) 1999 The Apache Software Foundation. All rights reserved.)

Example 5.5 JSP with Scriptlet Code

<html>
<head><title>Employee List</title></head>
<body>
<%-- Display All employees belonging to a department and earning at 
most the given salary --%>

<%   
    
    // Get the department for which the employees are
    // to be listed
    String deptidStr = request.getParameter( 
        Constants.REQ_DEPTID);

    // Get the max salary constraint
    String salaryStr = request.getParameter( 
        Constants.REQ_SALARY);

    // validate parameters

    // if salary or department not specified, go to
    // error page
    if ( (deptidStr == null) || (salaryStr == null ) )
    { 
       request.setAttribute(Constants.ATTR_MESSAGE, 
        "Insufficient query parameters specified" + 
        "(Department and Salary)");
       request.getRequestDispatcher("/error.jsp").
         forward(request, response);
    }

    // convert to numerics
    int deptid = 0;
    float salary = 0;
    try
    {
        deptid = Integer.parseInt(deptidStr);
        salary = Float.parseFloat(salaryStr);
    }
    catch(NumberFormatException e)
    {   
       request.setAttribute(Constants.ATTR_MESSAGE, 
          "Invalid Search Values" + 
          "(department id and salary )");
       request.getRequestDispatcher("/error.jsp").
          forward(request, response);        
}

    // check if they within legal limits
    if ( salary < 0  )
    {
      request.setAttribute(Constants.ATTR_MESSAGE, 
        "Invalid Search Values" + 
        "(department id and salary )");
      request.getRequestDispatcher("/error.jsp").
        forward(request, response);
    }
    
%>

<h3><center> List of employees in department # 
  <%=deptid%> earning at most <%= salary %>. </h3>

<%
    Iterator employees = new EmployeeDelegate().
                            getEmployees(deptid);
%>

<table border="1" >
    <tr>
        <th> First Name </th>
        <th> Last Name </th>
        <th> Designation </th>
        <th> Employee Id </th>
        <th> Tax Deductibles </th>
        <th> Performance Remarks </th>
        <th> Yearly Salary</th>
    </tr>
<%    
    while ( employees.hasNext() )
    {
        EmployeeVO employee = (EmployeeVO) 
                                employees.next();

        // display only if search criteria is met
        if ( employee.getYearlySalary() <= salary )
        {
%>
        <tr>
          <td> <%=employee.getFirstName()%></td>
          <td> <%=employee.getLastName()%></td>
          <td> <%=employee.getDesignation()%></td>
          <td> <%=employee.getId()%></td>
          <td> <%=employee.getNoOfDeductibles()%></td>
          <td> <%=employee.getPerformanceRemarks()%>
                </td>
          <td> <%=employee.getYearlySalary()%></td>
        </tr>
<%  
        }
    }
%>
</table>

<%@ include file="/jsp/trace.jsp" %>
<P> <B>Business logic and presentation formatting are 
  intermingled within this JSP view. </B>

</body>
</html>

Example 5.6 JSP with Scriptlet Code Extracted

<%@ taglib uri="/WEB-INF/corepatternstaglibrary.tld" 
    prefix="corepatterns" %>
<html>
<head><title>Employee List</title></head>
<body>

<corepatterns:employeeAdapter />

<h3><center>List of employees in 
  <corepatterns:department attribute="id"/> 
  department - Using Custom Tag Helper Strategy </h3>

<table border="1" >
    <tr>
        <th> First Name </th>
        <th> Last Name </th>
        <th> Designation </th>
        <th> Employee Id </th>
        <th> Tax Deductibles </th>
        <th> Performance Remarks </th>
        <th> Yearly Salary</th>
    </tr>
    <corepatterns:employeelist id="employeelist_key">
    <tr>
      <td><corepatterns:employee 
            attribute="FirstName"/></td>
      <td><corepatterns:employee 
            attribute="LastName"/></td> 
      <td><corepatterns:employee
            attribute="Designation"/> </td>
        <td><corepatterns:employee 
            attribute="Id"/></td> 
        <td><corepatterns:employee 
            attribute="NoOfDeductibles"/></td>
        <td><corepatterns:employee 
            attribute="PerformanceRemarks"/></td>
        <td><corepatterns:employee 
            attribute="YearlySalary"/></td>
        <td>
     </tr>
    </corepatterns:employeelist>
</table>

</body>
</html>

Example 5.7 Tight Coupling between a Domain Object and HttpServletRequest object

/** The following excerpt shows a domain object that 
  is too tightly coupled with HttpServletRequest **/
public class Customer
{ 
  public Customer ( HttpServletRequest request )
  { 
       firstName = request.getParameter("firstname"); 
       lastName = request.getParameter("lastname ");
  }
}

Example 5.8 Reduced Coupling between a Domain Object and HttpServletRequest object

// Domain Object not coupled with HttpServletRequest 
public class Customer
{ 
  public Customer ( String first, String last )
  { 
    firstName = first;
    lastName = last;
  }
}

Example 5.9 Conversion Logic Embedded Within View

<html>
<head><title>Employee List</title></head>
<body>

<h3><head><center> List of employees</h3>

<%
    String firstName = 
      (String)request.getParameter("firstName");
    String lastName  = 
      (String)request.getParameter("lastName");
    if ( firstName == null ) 
      // if none specific, fetch all
      firstName = "";
    if ( lastName == null )
      lastName = "";

    EmployeeDelegate empDelegate = new 
            EmployeeDelegate();
    Iterator employees = 
        empDelegate.getEmployees( 
          EmployeeDelegate.ALL_DEPARTMENTS);
%>

<table border="1" >
    <tr>
        <th> First Name </th>
        <th> Last Name </th>
        <th> Designation </th>
    </tr>
<%    
    while ( employees.hasNext() )
    {
        EmployeeVO employee = (EmployeeVO) 
                              employees.next();

        if ( employee.getFirstName(). 
              startsWith(firstName) && 
             employee.getLastName(). 
              startsWith(lastName) ) {
%>
 <tr>
  <td><%=employee.getFirstName().toUpperCase() %></td>
  <td> <%=employee.getLastName().toUpperCase() %></td>
  <td> <%=employee.getDesignation()%></td>
 </tr>
<%
        }
    }
%>
</table>

Example 5.10 Logic Extracted into Helper Classes

<html>
<head><title>Employee List - Refactored </title>
</head>
<body>

<h3> <center>List of employees</h3>

<corepatterns:employeeAdapter />

<table border="1" >
    <tr>
        <th> First Name </th>
        <th> Last Name </th>
        <th> Designation </th>
    </tr>

<corepatterns:employeelist id="employeelist" 
    match="FirstName, LastName">
<tr>

    <td><corepatterns:employee attribute= "FirstName" 
  case="Upper" /> </td>
    <td><corepatterns:employee attribute= "LastName" 
  case="Upper" /></td> 
    <td><corepatterns:employee attribute= 
  "Designation" /> </td>
    <td>
 </tr>
</corepatterns:employeelist>
</table>

Example 5.11 Controlling Access Using a Control Component

<%@ taglib uri="/WEB-INF/corepatternstaglibrary.tld" 
  prefix="corepatterns" %>
<corepatterns:guard/>
<html>
<head><title>Hide Resource from Client</title></head>
<body>

<h2>This view is shown to the client only if the 
control component allows access. The view delegates 
the control check to the guard tag at the top of the 
page.</h2>
</body>
</html>