Typical approach of using the servlets as controllers.

Enterprise Java
Architecting and Designing Scalable, Multitier Systems
by Michael Minh Nguyen
Listing 1. Typical approach of using the servlets as controllers.


package com.scalablemultitier;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class registerUserTypicalApproach extends HttpServlet
{
  private static final int MAX_FIRST_NAME_LENGTH_ALLOWED = 10;

  public void doPost (HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    User user;
    user = registerUser (request, response);
    if (user != null)
    {
      request.getSession (true).setAttribute ("User", user);
      request.getRequestDispatcher ("registrationSuccessful.jsp").
        forward (request, response);
    }
    else
    {
      request.getRequestDispatcher ("registrationFailed.jsp").
        forward (request, response);
    }
  }

  private User registerUser (HttpServletRequest request, HttpServlet-Response response)
  {
    User user = null;
    int length;
    String firstName, middleInitial, lastName, email;

    // 1. retrieve user registration data from 'request' object
    firstName = request.getParameter ("firstName");
    middleInitial = request.getParameter ("middleInitial");
    lastName = request.getParameter ("lastName");
    email = request.getParameter ("email");

    // 2. check to see user data is valid. Sample code below is done
    // only for firstName.
    // Actual program would include code for middle Initial, last
   // name and eMail.
    if (firstName == null)
    {
      return null;
    }
    length = firstName.trim ().length();
    if (length < 1 || length > MAX_FIRST_NAME_LENGTH_ALLOWED)
    {
      return null;
    }
    // 3. Implement controller logic to create beans such as session
   // bean, EJBs, and
    // regular beans as needed to register the user.
    // 4. return User bean if successful. Return null if failed.
    return user;
  }
}

About the Author

Michael Minh Nguyen is a senior software engineer at eBuilt Inc. in Irvine, CA. He may be contacted at [email protected].