Internet Applications Design Using J2EE Design Patterns (Core J2EE Patterns).

 

0.- Introduction.

1.- Design patterns.

2.- What Core J2EE Patterns are.

3.- Web applications design using Core J2EE Patterns.

4.- Core J2EE Patterns useful for web designing.

 

 

0.- Introduction.

 

Usually, web applications where jsp pages manage security services, contents recovery, and navigation are built. All this means a model with a high cost in maintenance, in which there are huge quantities of duplicated code in lots of jsp pages (a solution developed using the common technique of copying-pasting and some modifications).

The quality of these applications can be improved by centralising and encapsulating some of these mechanisms, making the application much more maintainable, simple, and clean, eliminating many scriplets (java code embedded in jsp pages). To achieve these objectives, there is nothing better than the condensed experience of many years of development and designing : J2EE design patterns.

 

1.- Design patterns.

1.1.- The concept of pattern.

We can say that since object-oriented development appeared, the discovery and use of design patterns has been one of the main innovations in software development.

Object-oriented development has had success due to the increase in the quality of software developed under this paradigm, making it more flexible, modular, reusable and comprehensible. Summing up, increasing its intern and extern quality (both related).

Classes and objects opened new ways of encapsulating abstractions, dividing the reality, and decreasing the complexity. Letting us focus our efforts on inherent concepts of the problem solving them in a more explicit way.

In this context, what design patterns have provided to us? These elements  have made possible the organisation of our classes in common and well proven structures; modificating the system to improve its flexibility and extensibility. In other words, increasing the easiness to adapt software to specification changes and its possible reutilisation. In some way, they have produced the same benefits as  the object-oriented programming but improving much more the design quality, and so, the software itself.

The idea of design pattern existed before becoming common in the computing community. It is commonly accepted, that the work that originated this discipline as it is nowadays known, was the book “Design Patterns: Elements of Reusable Object-Oriented Software” written by Gamma, Helm, Jonson, Vlissides, generally known as ‘GOF’.

This book proposes the following definition of the design pattern concept: “design patterns are descriptions of communications between objects and classes, that are adapted to solve a general design problem in a particular context”. So then, patterns appear focused on the applications micro-structure, classes and objects.

Looking at the GOF patterns catalogue it is to observe that many of them have a similar structure and produce a similar impact on the system. In order to have a clearer vision about the relationship between them, the concept of metapattern should be considered.

About patterns, it must be said that they are often grouped in “Pattern Languages”, defined as: “The specification of several patterns (elements and their relationships) in such a way that they can define good solutions to different problems that appear in a specific context”.

The main objective of the design patterns is to collect good practises that let us improve the quality of the systems design, determining objects which support useful roles in a specific context, encapsulating complexity and making it more flexible.

After having talked so much about patterns and, to better support these concepts, lets have a look at one of them:

Pattern: Strategy.

-         Intention: Defining an algorithms family, encapsulating each of them and making them interchangeable.

-         Applicability: Use it when…

o       Different variations of the same algorithm are needed.

o       Several subclasses only differ in their behaviour.

o       A class define several behaviours in multiple conditional sequences.

-         Structure: Firstly, there is an encapsulated algorithm in the “ClassXYZ”, but it is noticed that a more flexible design is needed because it is required to have the possibility of applicating different algorithms in execution time.

 

 

               à  à

 

The solution consists of taking out (uncouple) the algorithm that is encapsulated in “ClassXYZ”, defining a general interface (“AbstractAlgorithm”) for the algorithms group that we want to codificate,  and encapsulating each of them in a class (“Algorithm 1”, “Algorithm 2”, etc.), making them interchangeable.

1.2.- Why patterns are useful.

We have said that design patterns have contributed to make designs more flexible and extensible. Besides, they have proven to be a very useful (successful) way to reuse design, as they name, abstract and identify key aspects of common design structures, and as they are usually written in a specific way that makes easier their comprehension and application to developers as a group.

The benefits that a pattern produces can be measured in different ways:

-         They contribute to reuse design, identifying key aspects from the structure of a design that can be applicated in many different situations. The importance of reusing design is not low, as it has many advantages: it reduces the efforts in developing and maintenance, improves the security, the efficiency and the consistency of the designs, and reduces the cost of  investment.

-         They improve (increase, raise) the flexibility, modularity and extensibility. Intern factors and tightly related to the quality noticed by the user.

-         They increase the design vocabulary, helping us to design from a higher level of abstraction.

 

2.- What are Core J2EE Patterns.

 

The 8th of March, 2001, the Sun Java Centre published (as beta) a pattern catalogue.

The J2EE patterns describe usual problems found by business applications developers and give solutions to them. Essentially, these patterns contain the best solutions to help developers to design and build applications to the J2EE platform.

Although these patterns are represented from a logic level of abstraction, all of them have, in their original descriptions on the Sun website, several strategies which offer a huge quantity of details for their implementation.

During the 60 first days in which the patterns where at the disposal of the developers (in Html form), they were acceded more than 120.000 times. This is an evidence of how successful these solutions are within the java community.

 

 

3.- Web applications dessign using Core J2EE Patterns.

 

 

The design of web applications based on J2EE Patterns is organised around the use of different elements: a front controller, dispatchers, composite views, views (JSPs) and view helpers (JavaBeans).

All these elements can be organised as it follows, example of design based upon the J2EE patterns. Basically, it can be considered a pattern, the ‘Service-To-Worker Extended’:

 

 

Lets have a look to a basic description of these elements:

 

ServiceToWorker. It is a pattern that represents union as a solution to the patterns: controller, dispatcher, view and helper (considering that there are helpers for the controller, the dispatcher and the views). Basically, the mentioned design can be considered as an extended version of this pattern.

 

Lets see how all these elements interact:

 

 

The front controller  receives a request (for instance: www.MyApplicacion.com/controller?op=SeeRegister&id=58), it checks if the user has permission to execute the operation (showing the record whose id=58), and delegates its execution to the object Dispatcher. This one forms the composite view with static contents and calls the JSP in charged of displaying the records. The JSP page has all the HTML code used in displaying and gets the data that are to be displayed  calling a Bean, which is in communication with the data bases or other components that have the same function.

 

This structure is basically an implementation of the well known Model-View-Controller (MVC) architecture. In this model, the controller leaks the requests, extracts data, maps requests to commands, calls the suitable commands to manage those requests. TheView part determines the pages that are going to be visualised, and formats them to be seen. The client interacts with these views and makes http requests.

 

 

4.- Core J2EE Patterns useful for web designing.

 

In this section we are going to develop the main J2EE patterns for web applications, which are those we have used in the design presented before, in detail:

 

à Front Controller Pattern (Front controller). The http requests management to a web application (for instance www.MyApplication.com/controller?op=SeeRegister&id=58) can be centralised or distributed. As we have seen before, distributing the requests management in jsp pages leads to low quality applications, with a huge quantity of similar code distributed in all pages (views).

Solution: Using a controller in the initial point of the requests management. The controller manages these requests and realises some functions like: security restrictions verification, errors management, mapping and requests delegation to other components of the application that will be in charged of generating the suitable view for the user.

 

By centralising the decision and control points, the controller helps to reduce the quantity of java code embedded in the jsp pages (this code is usually known as Scriptlet). What we do is centralising control in the controller and reducing business logic in the views (a very good model of the metapattern ‘encapsulator/centralizer’ application).

 

 

 

The estandar controller implementation is usually a Servlet.

 

import javax.servlet.*;
import javax.servlet.http.*;
 
public class Controller extends HttpServlet {
 
    public void init(ServletConfig config) throws ServletException {
       super.init(config);
    }
 
    public void destroy() {
    }
 
    protected void doGet(HttpServletRequest request, 
        HttpServletResponse response)
        throws ServletException, java.io.IOException {
 
        processRequest(request, response);
    }
 
    protected void doPost(HttpServletRequest request, 
        HttpServletResponse response)
        throws ServletException, java.io.IOException {
 
        processRequest(request, response);
    }
     
    protected void processRequest(HttpServletRequest request, 
        HttpServletResponse response)
        throws ServletException, java.io.IOException {
 
        // gets the op parameter from the request 
        String action = request.getParameter("op") ;
        // the directory to which it will send the dispatched request 
        String dispatch ="/servlet/" ;
 
        // Depending on the past action it “dispatches” 
        // to a different servlet
        if(action == null)
            dispatch += "Inicio" ;
        else if(action.equals("VerRegistro"))
              dispatch += "VisualizarRegistro" ;
        else if(action.equals("ListRegistros"))
            dispatch += "ListarRegistros" ;
 
        // it creates a dispatcher to which resend the request 
        RequestDispatcher dispatcher = 
             request.getRequestDispatcher(dispatch) ;
 
        // it resends the request
        dispatcher.forward(request, response) ;
    }
 
    public String getServletInfo() {
        return "";
    }
}

 

 

Consequencies: control is centralised, security management is improved and the code reusability rises up.

 

à Dispacher View.

Context: the system controls the execution and access to the presentation processing flows. The latter is responsible of the dynamic generation of contents.

 

Problem: There is no centralised component for the access control management, the contents recovery or the views management, and there is some duplicated code in several views. Besides, the business logic and the format logic of the presentation are mixed in these views, making the system less flexible, less reusable, and, generally, less change resistant, reducing its modularity too, and providing a poor role division  between web production and the software development groups.

 

Solution: Combining a controller and a view dispatcher to manage the users’ requests and prepare a dynamic presentation as response. A dispatcher is responsible of the view management and the navigation, and it can be encapsulated inside a controller, a view, or as a separated component.

 

 

The implementation of the Dispatcher element is usually a Servlet that compares the parameters given by the user, and that calls the suitable JSP page, giving to it, at the same time, the necessary features to be executed and to show the suitable result. In a composite view setting it should form the latter.

 

Consequences: it centralises control and improves the reusability and the maintainability, improves the application partition  and the role division.

 

àViews (JSPs).

 

The views or JSPs are the way to separate the visualisation from the necessary business logic information to generate it, so the platform where those data are managed and the web server are independent.

 

JSPs are files usually formed by static HTML code, specific JSPs labels, and, optionally, parts of java code called ‘Scriptlets’. JSP pages are subjected to a translation phase and to a request processing phase. The translation phase is carried out only once. In case the JSP changes, this process will have to be repeated. Assuming there are no syntactic mistakes, this process result is a class file which implements the JSP functionality inside a servlet.

 

à Composite View.

 

Context: Sophisticated web applications present content from several data sources, using several sub views that form an only page to be visualised.

 

Solution: Using composite views that are formed by several atomic sub views. Each template component can be dynamically included in the whole, and the page schema can be managed independently from the content. This scenario occurs, for instance, in websites that include several independent sub views.

A web applications requirement is that their visualisation should have a similar structure all along the website. A template is a presentation component that forms a page with a specific design from separated views.

 

 

 

The classes design of this pattern is the following:

 

The mechanism to implement this pattern is based on the use of the <jsp:include> label, that can insert in the page both static and dynamic content when it is being served.

 

An example of a JSP page that implements a Composite View:

<%@ page contentType="text/html;charset=windows-1252"%>

<html>

<head>

<title>

Composite View

</title>

</head>

<body>

<%

  String sMainPanel;

  String sHeader, sFooter, sLeft, sRight, sArgs;

 

  sMainPanel = (String)request.getAttribute("mainPanel");

  sHeader = (String)request.getAttribute("header");

  sFooter = (String)request.getAttribute("footer");

  sLeft = (String)request.getAttribute("left");

  sRight = (String)request.getAttribute("right");

  sArgs = (String)request.getAttribute("args"); 

 

 

%>

<jsp:include page="<%= sHeader%>" flush="true"/>

<table width="100%">

  <tr align="left" valign="middle">

    <td width="20%">

    <jsp:include page="<%= sLeft%>" flush="true"/>

    </td>

    <td width="70%" align="center">

    <jsp:include page="<%= sMainPanel + "?" + sArgs %>" flush="true"/>

    </td>

    <td width="70%" align="right">

    <jsp:include page="<%= sRight%>" flush="true"/>

    </td>

  </tr>

</table>

<jsp:include page="<%= sFooter%>" flush="true"/>

</body>

</html>

 

 

Consequences: It improves the modularity and reusability, the flexibility and maintenance, and the manoeuvrability, it has a negative impact (very light) on the performance.

 

à View Helper.

 

Context: The system creates content presentations. This requires dynamic processing of the business data.

 

Problem: We usually tend to make changes to the presentation layer of an application. But this is difficult to do when the access to business data logic and the presentation format logic are mixed in this layer.

 

Solution: A view has the format code, delegating its processing responsibilities to its helper classes, that are generally implemented as JavaBeans (or custom tags). These helpers also keep the intermediate data models of the view and are used as adapters of the business data.

 

 

 

JAVABEANS:

 

JavaBeans are  java objects that follow a certain well-defined pattern: the bean encapsulates its properties making them private, and provides some public access methods (getter/setter) to read and modify the values of these properties.

 

Before acceding a Bean inside a JSP page, we need to identify it and create a reference to it. This can be done by using the <jsp:useBean…> label.

To get a bean property value we use the <jsp:getProperty name="user" property="name" /> label, and to modify it, the <jsp:setProperty name="user" property="name" value="<%=expression %>" /> label.

 

There it is an example of a JSP page that uses a JavaBean to show the content of an entry. We give it its ‘ID’ and get its properties: Name, Intern Code and Desctiption. The JavaBean implementation is very easy, as it is a class that, generally, uses de JDBC to access data bases, or that delegates the responsibility of reading these data by calling another component.

 

<%@ page  language="java"

          contentType="text/html;charset=ISO-8859-1"

          import="examples.SeeRegisterBean"

%>

<jsp:useBean id="SeeRegisterBean" scope="session" class="examples.SeeRegisterBean" />

<jsp:setProperty name="Id" property="<%= request.getParameter("id");%>" />

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Visualisation of the Register</title>

</head>

<body>

<table width="100%">

  <tr align="left" valign="middle">

    <td> Name: </td>

            <td>

                        <jsp:getProperty name="SeeRegisterBean" property="sName" />

    </td>

  </tr>

  <tr>

    <td> Intern Code: </td>

            <td>

                        <jsp:getProperty name="SeeRegisterBean" property="iCodInterno" />

    </td>

  </tr>

  <tr>

    <td> Description: </td>

            <td>

                        <jsp:getProperty name="SeeRegisterBean" property="sDesc" />

    </td>

  </tr>

</table>

</body>

</html>

 

Consequences: improves the application partition, its reusing, and its maintainability, and the roles division.

 

 

à Service to Worker.

 

Context: The system controls the execution and access to business data flow, from which the contents presentation is created.

 

Problem: The problem is a combination of the problems solved by the front controller and View helper patterns. There is no component that centralises the control access management, the content recovery, the management of the views, but there is a control code duplicated and spread through several views. Besides, the presentation logic and the presentation format logic are mixed in these views, making the system less flexible, less reusable and, generally, less change resistant.

 

Solution: Combining a controller, a dispatcher with views, and helpers to manage the clients requests, and prepare a dynamic presentation as response. The controllers delegate the content recovery to helpers. A dispatcher is the responsible of the views management and the navigation.

 

 

 

ã Moisés D. Díaz, www.moisesdaniel.com