Docstoc

22-Effective Web Architectures

Document Sample
22-Effective Web Architectures Powered By Docstoc
					Effective Web Architectures


       Written by Jeff Smith
          A Little Superficial History
   1978 - TCP/IP introduced
   1984 - DNS introduced
   1990 - Hypertext project first proposed at CERN
   1991 - First web server in USA (Stanford Linear Accelerator Center in
    Calif)
   1992 - World has 50 web servers!
   1994 - Marc Anderessen and Jim Clark form Netscape, David Filo and
    Jerry Yang create a search engine they call Yahoo
   1995 - First edition of Java (JDK) from Sun Microsystems
   1996 - First usable JDK 1.02
   1997 - Jeff Smith begins using Java!
   1998 - JDK 1.2 (Java 2) comes out
   2001 - JDK 1.4 comes out
   2004 - Google is now searching 3.3 billion web pages
   2006 – Good is now searching 25 billion web pages
                      Introduction
   Developing web applications in Java presents a developer
    with a myriad of architectural choices.
   Since there is no single architecture that is ideal for all
    applications and environments, it behooves a developer to
    understand a few of them so he can choose the appropriate
    architecture for the task at hand.
   These slides will discuss the following Java web
    architectures and the relative merits of each:
     JSP page centric architecture with scriptlets
     JSP page centric architecture with JavaBeans
     Servlet centric architectures


       It will also discuss how Oracle database code should be
        integrated into the servlet centric architecture.
      JSP Page Centric Architecture With Scriptlets -1




   This architecture may seem heretical to some Java
    architects, but for simple websites, a JSP centric
    architecture is acceptable.
   In fact, this architecture is so simple, it may not seem like an
    architecture at all. You just put together a couple of JSPs
    (and html) files and your website is ready to be deployed.
      JSP Page Centric Architecture With Scriptlets -2


   For example, you might create a website for your lemonade
    stand. This website might consist of a single web page
    about your lemonade stand with information about
   how many lemons you use
   the cost of a glass of lemonade
   a simple HTML form that customers can use to request
    more information.
   This HTML form could specify a JSP page (in its action
    parameter) to which it will submit its request information.
    This JSP page could incorporate scriptlet code which would
    then forward the information to you in the form of an email
    using JavaMail.
      JSP Page Centric Architecture With Scriptlets -3

   Here is the HTML page, lemonade.html, which submits its
    request to emailQuestion.jsp:
<html>
<head><title>Timmy and Susie's Lemonade Stand</title>
<body>
We use 3 fresh lemons per glass of lemonade<br>
Each glass of lemonade costs 50 cents<br>
<form action='emailQuestion.jsp'>
  Your name: <input type='text' name='YourName'><br>
  Your email: <input type='text' name='YourEmail'><br>
  Your question: <input type='text' name='Question'><br>
  <input type=submit value='Ask Us'>
</form>
</body>
</html>
      JSP Page Centric Architecture With Scriptlets -4

   This beautiful website looks like this:
       JSP Page Centric Architecture With Scriptlets -5

   The JSP page, emailQuestion.jsp, could contain scriptlet
    code like this:
<HTML>
<%@ page   import="java.util.*, java.io.*" %>
<%@ page   import="javax.mail.*, javax.mail.internet.*" %>
<%
  String   yourName = request.getParameter("YourName");
  String   toAddress = request.getParameter("YourEmail");
  String   question = request.getParameter("Question");

    try
    {
      String mailServer = "mail.lemonade.com";
      String subject = "RE: lemonade question";
      String fromAddress = "jeff@softtechdesign.com";
    JSP Page Centric Architecture With Scriptlets -6
//create mail session
Properties mailProps = new Properties();
mailProps.put("mail.smtp.host", mailServer);
Session mailSession =
          Session.getDefaultInstance(mailProps, null);

   //create mail mime message
 Message mimeMessage = new MimeMessage(mailSession);
 mimeMessage.setFrom(new InternetAddress(fromAddress));
 mimeMessage.setRecipient(Message.RecipientType.TO,
                       new InternetAddress(toAddress));
 mimeMessage.setSubject(subject);
 mimeMessage.setText(question);
 Transport.send(mimeMessage);
}
     JSP Page Centric Architecture With Scriptlets -7



  catch (Exception e)
  {
%>
    <%= e.getMessage() %>
<%
  }
%>
Thank you for your question!
</HTML>
      JSP Page Centric Architecture With Scriptlets -8



   Each time this JSP is requested, the servlet container (e.g.
    Tomcat) checks to see if the page has been updated since it
    was last compiled. If it has changed, the container
    recompiles the JSP (turning it into a servlet) and then
    executes it.
   Granted, this is an extremely simple website, but there are
    many people who have a page or two for a “website”. For
    those people, this simple architecture is fine. They don’t
    need Struts, Java Server Faces (JSF), MVC, EJBs, or even
    servlets.
      JSP Page Centric Architecture With Scriptlets -9



   Here are the advantages of this architecture:
     Deployment only entails copying two files to the servlet
       container (e.g. Tomcat)
     No need to edit web.xml descriptor files
     No need to restart Tomcat (this can be a problem on
       shared servers where bouncing Tomcat affects many
       users)
     Very quick to write (since there are just two files)
        JSP Page Centric Architecture With Scriptlets -10

   Here are some disadvantages of this architecture:
        JSP scriptlet code is tedious to write (for example, lining up all the
         <% and %> tags correctly).
        Since your email code isn’t in a proper class, you can’t easily reuse
         it elsewhere (can’t utilize inheritance or implement interfaces)
        Your Java (scriptlet) code and HTML are tightly coupled and cannot
         be worked on separately. Often times Java programmers aren’t the
         best web page designers, and many web page designers don’t
         know Java)
        If your website is large and complex, it is difficult to manage all the
         interdependencies with this architecture.


   In summary, this architecture is well suited for simple
    websites or for developing prototypes for more complex
    sites. It is not an advisable architecture for a complex
    website.
     JSP Page Centric Architecture With JavaBeans -1




   As an alternative to writing scriptlet code, you can separate
    your HTML from your Java code by writing JavaBeans and
    using JSP tags to access them.
   By moving your Java code into a separate class, you can
    use the full bag of Java tricks like inheritance, interfaces,
    etc.
   Moreover, you can test and debug your JavaBean class in a
    programmer friendly integrated development environment
    (IDE) like Eclipse or IntelliJ Idea.
     JSP Page Centric Architecture With JavaBeans -2



   A JavaBean is simply a class that:
     Has a no argument constructor
     Uses getter and setter methods to access all fields
     Implements the Serializable interface
     Can optionally use events to communicate with other
       beans

   The next slide contains an example of a JavaBean, a
    LoginBean class, that creates a single property (username)
    that is defaulted to “guest” in the constructor:
    JSP Page Centric Architecture With JavaBeans -3
package com.cexp.wms.login;
public class LoginBean implements java.io.Serializable
{
  private String username;
  public LoginBean() //constructor takes no arguments
  {
    this.username = "guest"; //assign default value
  }
  public String getUsername()
  {
    return username;
  }
  public void setUsername(String username)
  {
    this.username = username;
  }
}
     JSP Page Centric Architecture With JavaBeans -4


The JSP page that uses this JavaBean might look like:


<HTML><BODY>
  <jsp:useBean id="login" scope="session"
   class="com.cexp.wms.login.LoginBean"/>
  <jsp:setProperty name="login" property="username"
   value="jsmith"/>
  <b>
    Welcome to our website,
    <jsp:getProperty name="login" property="username"/>
  </b>
</BODY></HTML>
     JSP Page Centric Architecture With JavaBeans -5



   The <jsp:useBean> tag declares the bean to be used with
    this page, and identifies this bean as "login".
   The <jsp:setProperty> tag provides access to the
    "username" property and assigns it the value of the "jsmith"
    parameter passed into the page via a URL query string.
    This invokes the setUserName() method inside the class.
   For example, if the URL requesting this page was
    'http://www.mydomain.com/login.jsp?username=Jeff', the
    query string is "username=Jeff" and the following HTML
    would appear in the user's browser:
    Welcome to our website, Jeff
     JSP Page Centric Architecture With JavaBeans -6

   Note that for our convenience, JSP tag attributes can be in
    double quotes or single quotes (just like HTML form fields).
    You can also imbed scriptlet code in a JSP tag to access
    form fields like so:
<HTML>
<BODY>
  <jsp:useBean id="login" scope="session"
   class="com.cexp.wms.login.LoginBean"/>
  <jsp:setProperty name="login" property="username"
     value='<%= request.getParameter("username") %>'/>

  Welcome to our website, <jsp:getProperty name="login"
   property="username"/>
</BODY>
</HTML>
     JSP Page Centric Architecture With JavaBeans -7

   To test this page, I compiled the JavaBean class and copied
    it to my Tomcat context called wms:
     JSP Page Centric Architecture With JavaBeans -8

   After restarting Tomcat (so it reloads my LoginBean class), I
    invoked the JSP from my web browser:
      JSP Page Centric Architecture With JavaBeans -9
   One Tomcat limitation to keep in mind is that each time you
    change your JavaBean class (or any other class used by
    your web application), you will have to restart (bounce)
    Tomcat in order to force Tomcat to load the new version of
    the class.
   Setting “reloadable=true” won’t make any difference (at
    least with Tomcat version 4.124). This is an annoying
    problem when you are working on a shared Tomcat
    instance (it wouldn’t be a good idea to bounce Tomcat in the
    middle of a credit card transaction, for example).
   Note that you can force Tomcat to reload your classes using
    the manager like so:

    http://10.128.1.121:8080/manager/reload?path=/wms
    (tomcat will prompt you for your username/password)
     JSP Page Centric Architecture With JavaBeans -10
   This limitation doesn’t apply to JSPs. Any Java scriptlet
    code you have imbedded in a JSP will automatically be
    recompiled the first time the JSP is accessed (after you
    copy it to the server).
   To simplify accessing JavaBeans from your JSPs, you
    should consider using the Java standard tag library (JSTL).
    In many JSPs, JSTL tags can replace the more awkward
    getProperty() and setProperty() JSP tags.
   JSTL can also eliminate the need for scriptlet code in many
    places, as its expression language (EL) syntax makes it
    easy to iterate through lists, Collections and arrays.
   JSTL also provides support for internationalization (I18N),
    formatting action tags for dates and numbers, SQL action
    tags for database access, and XML tags for parsing and for
    XSLT transformations. You can learn more about JSTL on
    Sun’s website at http://java.sun.com/products/jsp/jstl/.
     JSP Page Centric Architecture With JavaBeans -11
   In summary, incorporating JavaBeans into your JSPs requires a little
    more upfront time since you have to write both the bean class and the
    HTML file. However, by isolating the Java code (the website
    implementation) from the HTML (website presentation) we achieve the
    following advantages:
        We create a bean class that can be reused in other JSP pages (for
         example, we wouldn’t have to copy and paste login code into
         numerous JSP pages)
        We enable one person to write the Java code (the bean) and
         another person (perhaps a non-Java web designer) to create the
         web page layout.
        We can test and debug our Java code in a programmer friendly
         environment like Eclipse
        Our beans can be created and managed by servlets (see the servlet
         centric architecture section below)
   Real-world, complex websites are usually developed using this
    methodology: the Java code is separated from the HTML presentation.
               Servlet Centric Architectures -1
   Instead of submitting HTML form requests to JSPs, you can
    submit them to Servlets instead. Servlets are just server
    side Java classes that usually extend the HttpServlet class
    and have doGet() and doPost() methods which can be
    implemented to process HTML requests. Since they are just
    regular classes, you can compile and test them in your
    favorite IDE.
   You could put all your business logic, database code, and
    presentation code within your servlet’s doGet() or doPost()
    method, but this is a bad idea. In general, it is preferable to
    keep your servlet classes as lean as possible. Good object
    oriented program (OOP) design would suggest that your put
    your business logic in a separate class and have your
    doGet() or doPost() method invoke that code.
               Servlet Centric Architectures -2


   By separating the web application into layers like this, you
    obtain the following advantages:
     You can write and debug your business classes
       separately. Just add a main method to the business
       class and you can test the various methods without
       having to test them through a web browser
     You can re-use your business class in other applications
       (including non-web applications)
     You can more easily divide the work up among multiple
       programmers
               Servlet Centric Architectures -3
   Servlets can directly return HTML using System.out.println()
    statements like so:

public void doPost(HttpServletRequest request,
                   HttpServletResponse response)
   throws ServletException, IOException
{
  response.setContentType("text/html");
  PrintWriter out = new
                PrintWriter(response.getOutputStream());
  out.println("<html>");
  out.println("Hello world");
  out.println("</html>");
}

   As you can see, this is an awkward way to return HTML.
               Servlet Centric Architectures -4

   In practice, it is much better to put the presentation logic
    and HTML in a JSP and simply have the Servlet forward this
    page back to the browser. These JSP pages could then be
    developed in a slick tool like Dreamweaver.
   Instead, the servlet should act like a controller and
     process incoming requests from your web pages and
        invoke the appropriate code in your business classes.
        The business classes should access the database tier
        (when necessary) and wrap up any data they need to
        return to the web browser in the form of JavaBeans.
     forward the request (and JavaBeans) to a JSP which
        would format a pretty page to be sent back to the web
        browser.
                 Servlet Centric Architectures -5
   So how does a servlet forward a request (and JavaBean) to
    a JSP? It adds a JavaBean object to the request object and
    then creates a RequestDispatcher object to forward the
    request like so:

  //musicDB object retrieves songs from DB, storing
  //them as an array list of song beans
ArrayList songList = musicDB.searchForSongs(songIDs);

 //add songList object to request object
request.setAttribute("songs", songList);

RequestDispatcher dispatcher =
   getServletContext().getRequestDispatcher("/ShowSongs.jsp");
dispatcher.forward(request, response);

   ShowSongs.jsp will render the list of song beans objects (using JSTL)
               Servlet Centric Architectures -6

   While this architecture may seem complex, it actually
    simplifies the development and testing of large websites
    since each layer can be written and tested independently
    (and by different groups of people).
     For example, the MusicDatabase class can be unit
        tested without the servlet or JSP pages
   Many web applications use a single servlet to act as the
    controller. Hence the doPost() or doGet() methods of these
    servlets may have many logic branches (one branch for
    each web action).
   For example, your doPost() method might look something
    like:
      (see next slide)
             Servlet Centric Architectures -7
public void doPost(HttpServletRequest request,
                   HttpServletResponse response)
   throws ServletException, IOException
{
  if (isCarLoanRequest(request))
    processCarLoanRequest(request, response);
  else if (isTractorLoanRequest(request))
    processTractorLoanRequest(request, response);
  else if (isPriceQuoteRequest(request))
    processPriceQuoteRequest(request, response);
  else
    ...
    100 more web actions!
}
             Servlet Centric Architectures -8


public boolean isCarLoanRequest(HttpServletRequest req)
throws IOException
{
  //if “car” parameter exists, then request came from
  //car loan request web form
  if (req.getParameter(“car”) == null) //no car param!
    return(false);
  else
    return(true);
}
                            }
                 Servlet Centric Architectures -9
   Note that the process methods above would in turn create and use
    business objects to carry out the request(s).
   Also note that the request object passed into the doPost() method
    contains all the request information, including HTML form field(s)
    information, cookies, and other browser information. Your Java code
    can interrogate this request object to determine how to process the
    request.
   For example, if the request object contains car loan request HTML form
    fields, your servlet could process a car loan. If it contains price quote
    request HTML form fields, your servlet could process a price quote
    request. Sometimes it is advisable to add hidden fields to HTML forms
    to label the form and make it easy for a servlet to know how to process
    it. For example, a car loan request HTML form could contain the
    following hidden field:

<input type=hidden name=CAR_LOAN_REQUEST_FORM value=Y>
                 Servlet Centric Architectures -10

   For large websites, this if-else statement could be quite long and
    involved.
   To simplify this aspect of the servlet centric architecture, a framework
    like Struts or Java Server Faces can be quite helpful. Rather than write
    complicated if-else statements, you would write action mappings in a
    configuration (xml) file. Since this configuration file is parsed at runtime,
    you can also dynamically re-map web request actions at runtime without
    having to recompile your servlet and bounce your servlet container.
   To learn more about Struts, you can look at
    http://jakarta.apache.org/struts.
   To learn more about Java Server Faces (JSF), you can look at
    http://java.sun.com/j2ee/javaserverfaces.
   If you're starting a new project (and can choose whichever framework
    you want), I'd recommend choosing JSF. I believe it will replace Struts
    as the dominant web framework within a year.
               Servlet Centric Architectures -11



   Another advantage of using a single servlet as your
    controller is that you can add code (in one place) that will
    execute before or after any request is processed.
   For example, you may want your servlet to ensure that the
    person making the request has logged into your web
    application before allowing them to access any of the
    pages.
   With a single servlet controller, this is easy to implement:
    (see next slide)
              Servlet Centric Architectures -12
public void doPost(HttpServletRequest request,
                   HttpServletResponse response)
   throws ServletException, IOException
{
    //detour user to log in page
  if (isUserLoggedIn(request) == false)
    forwardToLogInPage(request, response);

    if (isCarLoanRequest(request))
      processCarLoanRequest(request, response);
    else if (isTractorLoanRequest(request))
      processTractorLoanRequest(request, response);
    else if (isPriceQuoteRequest(request))
      processPriceQuoteRequest(request, response);
    else
      ...
}
                      Database Access -1
   So where does the database code fit into all of this?
   If you are connecting to Oracle or MySQL using JDBC (or a
    JDBC framework), one effective design involves creating a
    database class (like the MusicDatabase class referred to in
    a previous slide) whose constructor establishes a
    connection (or a connection pool) to the database.
   For simple applications, the methods of this database class
    could be called directly from the servlet. For more complex
    applications that require a business tier, you might have
    business objects (e.g. an Employee class or an Order class)
    invoke these methods
   You could create this database object in the init() method of
    your servlet and then close this database connection in the
    servlet’s destroy() method. Here’s a code example that
    creates a music database object: (see next slide)
                  Database Access -2
private MusicDatabase musicDB = null;

public void init(ServletConfig config)
   throws ServletException
{
  super.init(config);

 //create plain old Java object (POJO), a MusicDatabase
 //object, whose constructor will create a db connection
  musicDB = new MusicDatabase();
}

public void destroy()
{
  //close db when the servlet is unloaded from Tomcat
   musicDB.closeConnection();
}
                      Database Access -3
   By creating your database object (and hence database
    connection) in the init() method, you avoid having to pay the
    time penalty of having to create a database connection on
    the fly each time a request comes in that requires database
    access.
   With an pre-existing database connection, your database
    operations should be very quick.
   With this architecture, you can also change your
    persistence layer without affecting the other layers (e.g. the
    MusicDatabase class has a searchForSongs() method--the
    caller of this method has no idea whether the method uses
    JDBC, SQLExecutor, Hibernate, or Entity beans).
   For example, changing the persistence layer from POJOs to
    EJBs will not affect the code in your servlet controller or
    JSPs.
                      Database Access -4
public class MusicDatabase
{
  ConnectionPool conPool = null;
  public MusicDatabase()
  {
    String driverName = "oracle.jdbc.driver.OracleDriver";
    String connURL = "jdbc:oracle:thin:@MYSERVER:1521:WDEV";
    String username = "user";
    String password = "pwd";

      conPool = new ConnectionPool(1, driverName, connURL,
                                   username, password);
  }

  public ArrayList searchForSongs(ArrayList songIDs)
  {
    ArrayList songList = new ArrayList();
    ...searches DB & populate ArrayList w/ SongBean objects
    ...
                      Database Access -5
   Here is a high level diagram of the servlet centric
    architecture with a separate business layer and database
    access layer:




   For complex websites, the servlet centric architecture is the
    most flexible and has the cleanest separation of
    presentation logic from business logic. Moreover, it allows
    different people to work on different layers of the website
    with the smallest probability of coding conflicts.
                       Final Summary


   One size, or architecture, does not fit all in the web
    development world.
   For simple websites that you want to create quickly, a JSP
    centric architecture with Java scriptlet code can be best.
   If you want to develop a simple website quickly, but want
    your Java code to be in separate classes, the
    JSP/JavaBean architecture is efficient.
   And for complex websites that require the talents of many
    people, a servlet centric architecture is ideal.
     If you employ this latter architecture for a very large
        website, you would be wise to consider using Java
        Server Faces (JSF).

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:4
posted:5/15/2012
language:English
pages:42
fanzhongqing fanzhongqing http://
About