Home > Articles > Programming > Java

J2EE Presentation Tier Design Considerations

📄 Contents

  1. Presentation Tier Design Considerations
  2. Presentation Tier Bad Practices
  • Print
  • + Share This
In this sample chapter the authors discuss the design issues developers need to consider when they the presentation patterns that appear in the catalog in this book.
This sample chapter is excerpted from Core J2EE Patterns: Best Practices and Design Strategies, by Deepak Alur, John Crupi, and Dan Malks.
This chapter is from the book

Presentation Tier Design Considerations

When developers apply the presentation patterns that appear in the catalog in this book, there will be adjunct design issues to consider. These issues relate to designing with patterns at a variety of levels, and they may affect numerous aspects of a system, including security, data integrity, manageability, and scalability. We discuss these issues in this chapter.

Although many of these design issues could be captured in pattern form, we chose not to do so because they focus on issues at a lower level of abstraction than the presentation patterns in the catalog. Rather than documenting each issue as a pattern, we have chosen to document them more informally: We simply describe each issue as one that you should consider when implementing systems based on the pattern catalog.

Session Management

Session State on Client

There are benefits to persisting session state on the client:

  • It is relatively easy to implement.

  • It works well when saving minimal amounts of state.

Additionally, this strategy virtually eliminates the problem of replicating state across servers in those situations that implement load balancing across physical machines.

There are two common strategies for saving session state on the client—HTML hidden fields and HTTP cookies—and we describe these strategies below. A third strategy entails embedding the session state directly into the URIs referenced in each page (for example, <form action=someServlet?var1=x&var2=y method=GET>). Although this third strategy is less common, it shares many of the limitations of the following two methods.

HTML Hidden Fields

Additionally, when you utilize hidden fields to save session state, the persisted state is limited to string values, so any object references must be "stringified". It is also exposed in clear text in the generated HTML source, unless specifically encrypted.

HTTP Cookies

We also run into size and type limitations when saving session state on the client. There are limitations on the size of cookie headers, and this limits the amount of data that can be persisted. Moreover, as with hidden fields, when you use cookies to save session state, the persisted state is limited to stringified values.

Security Concerns of Client-Side Session State

Although saving session state on the client is relatively easy to implement initially, it has numerous drawbacks that take time and thought to overcome. For projects that deal with large amounts of data, as is typical with enterprise systems, these drawbacks far outweigh the benefits.

Session State in the Presentation Tier

  • A predefined session timeout is exceeded.

  • The session is manually invalidated.

  • The state is removed from the session.

Note that after a server shutdown, some in-memory session management mechanisms may not be recoverable.

It is clearly preferable for applications with large amounts of session state to save their session state on the server. When state is saved on the server, you are not constrained by the size or type limitations of client-side session management. Additionally, you avoid raising the security issues associated with exposing session state to the client, and you do not have the performance impact of passing the session state across the network on each request.

You also benefit from the flexibility offered by this strategy. By persisting your session state on the server, you have the flexibility to trade off simplicity versus complexity and to address scalability and performance.

If you save session state on the server, you must decide how to make this state available to each server from which you run the application. This issue is one that requires you to deal with the replication of session state among clustered software instances across load-balanced hardware, and it is a multidimensional problem. However, numerous application servers now provide a variety of out-of-the-box solutions. There are solutions available that are above the application server level. One such solution is to maintain a "sticky" user experience, where you use traffic management software, such as that available from Resonate [Resonate], to route users to the same server to handle each request in their session. This is also referred to as server affinity.

Another alternative is to store session state in either the business tier or the resource tier. Enterprise JavaBeans components may be used to hold session state in the business tier, and a relational database may be used in the resource tier. For more information on the business-tier option, please refer to "Using Session Beans" on page 55.

Controlling Client Access

One reason to restrict or control client access is to guard a view, or portions of a view, from direct access by a client. This issue may occur, for example, when only registered or logged-in users should be allowed access to a particular view, or if access to portions of a view should be restricted to users based on role.

After describing this issue, we discuss a secondary scenario relating to controlling the flow of a user through the application. The latter discussion points out concerns relating to duplicate form submissions, since multiple submissions could result in unwanted duplicate transactions.

Guarding a View

One common way of dealing with this issue is to use a controller as a delegation point for this type of access control. Another common variation involves embedding a guard directly within a view. We cover controller-based resource protection in "Presentation Tier Refactorings" on page 73 and in the patterns catalog, so we will focus here on view-based control strategies. We describe these strategies first, before considering the alternative strategy of controlling access through configuration.

Embedding Guard Within View

Including an All-or-Nothing Guard per View

Example 3.1 Including an All-or-Nothing Guard per View

<%@ taglib uri="/WEB-INF/corej2eetaglibrary.tld"
  prefix="corePatterns" %>

Including a Guard for Portions of a View

Portions of View Not Displayed Based on User Role

Example 3.2 Portions of View Not Displayed Based on User Role

<%@ taglib uri="/WEB-INF/corej2eetaglibrary.tld"
  prefix="corePatterns" %>

<corePatterns:guard role="manager">
<b>This should be seen only by managers!</b>
Portions of View Not Displayed Based on System State or Error Conditions

Guarding by Configuration

The basic and form-based authentication methods, also described in the Servlet specification, rely on this security information. Rather than repeat the specification here, we refer you to the current specification for details on these methods. (See http://java.sun.com/ products/servlet/index.html.)

So that you understand what to expect when adding declarative security constraints to your environment, we present a brief discussion of this topic and how it relates to all-or-nothing guarding by configuration. Finally, we describe one simple and generic alternative for all-or-nothing protection of a resource.

Resource Guards via Standard Security Constraints

The role name is "sensitive" and the restricted resources are named sensitive1.jsp, sensitive2.jsp, and sensitive3.jsp. Unless a user or group is assigned the "sensitive" role, then clients will not be able to directly access these Java Server Pages (JSPs). At the same time, since internally dispatched requests are not restricted by these security constraints, a request that is handled initially by a servlet controller and then forwarded to one of these three resources will indeed receive access to these JSPs.

Finally, note that there is some inconsistency in the implementation of this aspect of the Servlet specification version 2.2 across vendor products. Servers supporting Servlet 2.3 should all be consistent on this issue.

Example 3.3 Unassigned Security Role Provides All-or-Nothing Control

   		<description>A Collection of Sensitive Resources
Resource Guards via Simple and Generic Configuration

Direct public access is disallowed to the /WEB-INF/ directory, its subdirectories, and consequently to info.jsp. On the other hand, a controller servlet can still forward to this resource, if desired. This is an all-or-nothing method of control, since resources configured in this manner are disallowed in their entirety to direct browser access.

For an example, please refer to "Hide Resource From a Client" on page 100.

Duplicate Form Submissions

Synchronizer (or D_ vu) Token

On the other hand, if the two token values match, then we are confident that the flow of control is exactly as expected. At this point, the token value in the session is modified to a new value and the form submission is accepted.

You may also use this strategy to control direct browser access to certain pages, as described in the sections on resource guards. For example, assume a user bookmarks page A of an application, where page A should only be accessed from page B and C. When the user selects page A via the bookmark, the page is accessed out of order and the synchronizer token will be in an unsynchronized state, or it may not exist at all. Either way, the access can be disallowed if desired.

Please refer to "Introduce Synchronizer Token in the "Presentation Tier Refactorings section for an example of this strategy.


Detailed discussion of validation strategies is outside the scope of this book. At the same time, we want to mention these issues as ones to consider while designing your systems, and hope you will refer to the existing literature in order to investigate further.

Validation on Client

Validation on Server

Form-Centric Validation

To provide a more flexible, reusable, and maintainable solution, the model data may be considered at a different level of abstraction. This approach is considered in the following alternative strategy, "Validation Based on Abstract Types. An example of form-centric validation is shown in the listing in Example 3.4.

Example 3.4 Form-Centric Validation

/**If the first name or last name fields were left blank, then
 an error will be returned to client. With this strategy, these 
checks for the existence of a required field are duplicated. If 
this validation logic were abstracted into a separate component, 
it could be reused across forms (see Validation Based on Abstract 
Types strategy)**/
public Vector validate()
Vector errorCollection = new Vector();
		if ((firstname == null) ||
 (firstname.trim.length() < 1))
		 errorCollection.addElement("firstname required");
		if ((lastname == null) || (lastname.trim.length() < 1))
		 errorCollection.addElement("lastname required");
return errorCollection;
Validation Based on Abstract Types

The typing and constraints information is abstracted out of the model state and into a generic framework. This separates the validation of the model from the application logic in which the model is being used, thus reducing their coupling.

Model validation is performed by comparing the metadata and constraints to the model state. The metadata and constraints about the model are typically accessible from some sort of simple data store, such as a properties file. A benefit of this approach is that the system becomes more generic, because it factors the state typing and constraint information out of the application logic.

An example is to have a component or subsystem that encapsulates validation logic, such as deciding whether a string is empty, whether a certain number is within a valid range, whether a string is formatted in a particular way, and so on. When various disparate application components want to validate different aspects of a model, each component does not write its own validation code. Rather, the centralized validation mechanism is used. The centralized validation mechanism will typically be configured either programmatically, through some sort of factory, or declaratively, using configuration files.

Thus, the validation mechanism is more generic, focusing on the model state and its requirements, independent of the other parts of the application. A drawback to using this strategy is the potential reduction in efficiency and performance. Also, more generic solutions, although often powerful, are sometimes less easily understood and maintained.

An example scenario follows. An XML-based configuration file describes a variety of validations, such as "required field," "all-numeric field," and so on. Additionally, handler classes can be designated for each of these validations. Finally, a mapping links HTML form values to a specific type of validation. The code for validating a particular form field simply becomes something similar to the code snippet shown in Example 3.5.

Example 3.5 Validation Based on Abstract Types


Helper Properties—Integrity and Consistency

 <jsp:setProperty name="helper" property="*"/>

This tells the JSP engine to copy all matching parameter values into the corresponding properties in a JavaBean called "helper," shown in Example 3.6:

Example 3.6 Helper Properties - A Simple JavaBean Helper

public class Helper 
	private String first;
	private String last;

	public String getFirst()
		return first; 

	public void setFirst(String aString)

	public String getLast()
		return last; 

	public void setLast(String aString)


How is a match determined, though? If a request parameter exists with the same name and same type as the helper bean property, then it is considered a match. Practically, then, each parameter is compared to each bean property name and the type of the bean property setter method.

Although this mechanism is simple, it can produce some confusing and unwanted side effects. First of all, it is important to note what happens when a request parameter has an empty value. Many developers assume that a request parameter with an empty string value should, if matched to a bean property, cause that bean property to take on the value of an empty string, or null. The spec-compliant behavior is actually to make no changes to the matching bean property in this case, though. Furthermore, since JavaBean helper instances are typically reused across requests, such confusion can lead to data values being inconsistent and incorrect. Figure 3.1 shows the sort of problem that this might cause.

Figure 3.1 Helper properties.

Request 1 includes values for the parameter named "first" and the one named "last," and each of the corresponding bean properties is set. Request 2 includes a value only for the "last" parameter, causing only that one property to be set in the bean. The value for the "first" parameter is unchanged. It is not reset to an empty string, or null, simply because there is no value in the request parameter. As you can see in Figure 3.1, this may lead to inconsistencies if the bean values are not reset manually between requests.

Another related issue to consider when designing your application is the behavior of HTML form interfaces when controls of the form are not selected. For example, if a form has multiple checkboxes, it is not unreasonable to expect that unchecking every checkbox would result in clearing out these values on the server. In the case of the request object created based on this interface, however, there would simply not be a parameter included in this request object for any of the checkbox values. Thus, no parameter values relating to these checkboxes are sent to the server (see http://www.w3.org for full HTML specification).

Since there is no parameter passed to the server, the matching bean property will remain unchanged when using the <jsp:setProperty> action, as described. So, in this case, unless the developer manually modifies these values, there is the potential for inconsistent and incorrect data values to exist in the application. As stated, a simple design solution to this problem is to reset all state in the JavaBean between requests.

  • + Share This
  • 🔖 Save To Your Account