J2Ee Design Patterns: Intercepting Filter

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

J2EE DESIGN PATTERNS

First we sould start with what are design pattern? We can say a design pattern is simply a description of a recurring solution to a problem, given a context.The context is the environment, surroundings, situation, or interrelated conditions within which the problem exists.

Second why do need to use design patterns? Design patterns have a number of advantages like 1. Once described, any level engineer can use the pattern. 2. They allow for reuse without having to reinvent in every a project. 3. They allow to better define system structure. 4. They provide a design vocabulary. 5. They provide reusable artifacts. 6. Patterns can form frameworks that can then be used for implementations.

In this section we have tried to cover how to use and identify design patterns, in J2EE applications. The interest in design patterns has been around for a number of years in the software industry. However, interest among mainstream software developers is a fairly recent development actually it takes a highly experienced engineer to recognize a pattern, it requires collaboration, and it requires ongoing refinements.

There are a number of patterns that have been identified by the Sun Java Center for the presentation tier. We havve tried to explain them in this section , we are starting with a small explanation and then a complete section on each patterns.

Intercepting Filter : Facilitates preprocessing and post-processing of a request.

Front Controller : Provides a centralized controller for managing the handling of requests.

Composite View : Creates an aggregate View from atomic subcomponents.

View Helper : Encapsulates logic that is not related to presentation formatting into Helper
components.

Dispatcher View : Combines a Dispatcher component with the Front Controller and View Helper
patterns, deferring many activities to View processing.

Service to Worker : Combines a Dispatcher component with the Front


Controller and View Helper patterns.

Business Delegate : Reduces coupling between presentation-tier clients and business services. It
hides the underlying implementation details of the business service, such as lookup and access details of the EJB architecture.

Session Facade : Encapsulate the complexity of interactions between the business objects
participating in a workflow. The Session Facade manages the business objects, and provides a uniform coarse-grained service access layer to clients.

Service Locator : Multiple clients can reuse the Service Locator object to reduce code complexity,
provide a single point of control, and improve performance by providing a caching facility.

Transfer Object Assembler : It is used to build the required model or submodel. The Transfer
Object Assembler uses Transfer Objects to retrieve data from various business objects and other objects that define the model or part of the model.

Value List Handler :The most critical concern in a distributed paradigm is the latency time. Value
List Handler Pattern suggests an alternate approach of using ejb-finder methods. The pattern is used to control the search, cache the results and provide the results to the client using a lightweight mechanism.

Composite Entity : It model, represent, and manage a set of interrelated persistent objects rather
than representing them as individual fine-grained entity beans. A Composite Entity bean represents a graph of objects.

Transfer Object : Encapsulate the business data. A single method call is used to send and retrieve
the Transfer Object. When the client requests the enterprise bean for the business data, the enterprise bean can construct the Transfer Object, populate it with its attribute values, and pass it by value to the client.

Service Activator : Service Activator enables asynchronous access to enterprise beans and other
business services. It receive asynchronous client requests and messages. On receiving a message, the Service Activator locates and invokes the necessary business methods on the business service components to fulfill the request asynchronously. In EJB2.0, Message Driven beans can be used to implement Service Activator for message based enterprise applications. The Service Activator is a JMS Listener and delegation service that creates a message faade for the EJBs.

Data Access Object : Abstracts and encapsulate all access to the data source. The DAO manages
the connection with the data source to obtain and store data.

EE DESIGN PATTERNS - Intercepting Filters


Different type of processing is required for the different type of request received by the presentation tier request handler. Some requests are simply forwarded to the appropriate handler component, while other requests must be processed being further processed. We require Preprocessing and post-processing of a client Web request and response.

We require a common processing, such as checking the data-encoding scheme or logging information about each request, completes per request. Centralization of common logic is desired. Services should be easy to add or remove unobtrusively without affecting existing components, so that they can be used in a variety of combinations, such as Logging and authentication, Debugging and transformation of output for a specific client, Uncompressing and converting encoding scheme of input

Solution is to Create pluggable filters to process common services in a standard manner without requiring changes to core request processing code. The filters intercept incoming requests and outgoing responses, allowing preprocessing and post-processing. We are able to add and remove these filters unobtrusively, without requiring changes to our existing code.

We are able, in effect, to decorate our main processing with a variety of common services, such as security, logging, debugging, and so forth. These filters are components that are independent of the main application code, and they may be added or removed declaratively. For example, a deployment configuration file may be modified to set up a chain of filters. The same configuration file might include a mapping of specific URLs to this filter chain. When a client requests a resource that matches this configured URL mapping, the filters in the chain are each processed in order before the requested target resource is invoked.

Intecepting filters centralizes control with Loosely Coupled Handlers, Filters provide a central place for handling processing across multiple requests, as does a controller. Filters are better suited to massaging requests and responses for ultimate handling by a target resource, such as a controller. Additionally, a controller often ties together the management of numerous unrelated common services, such as authentication, logging, encryption, and so forth, while filtering allows for much more loosely coupled handlers, which can be combined in various combinations.

Intercepting filters improves reusability, Filters promote cleaner application partitioning and encourages reuse. These pluggable interceptors are transparently added or removed from existing code, and due to their standard interface, they work in any combination and are reusable for varying presentations.

Intercepting filters provide Declarative and Flexible Configuration, Numerous services are combined in varying permutations without a single recompile of the core code base.

But Sharing information between filters can be inefficient, since by definition each filter is loosely coupled. If large amounts of information must be shared between filters, then this approach may prove to be costly.

The responsibilities of the components participating in this patterns are :

FilterManager :The FilterManager manages filter processing. It creates the FilterChain with the appropriate filters, in the correct order, and initiates processing.

FilterChain : The FilterChain is an ordered collection of independent filters.

Filters : These are the individual filters that are mapped to a target. The FilterChain coordinates their processing.

Target : The Target is the resource requested by the client.

Strategies-

Custom Filter Strategy: Filter is implemented via a custom strategy defined by the developer. This is less flexible and less powerful than the preferred Standard Filter Strategy. The Custom Filter Strategy is less powerful because it cannot provide for the wrapping of request and response objects in a standard and portable way. Additionally, the request object cannot be modified, and some sort of buffering mechanism must be introduced if filters are to control the output stream. To implement the Custom Filter Strategy, the developer could use the Decorator pattern [GoF] to wrap filters around the core request processing logic.

Standard Filter Strategy : Filters are controlled declaratively using a deployment descriptor, as described in the servlet specification version 2.3. The Servlet 2.3 specification includes a standard mechanism for building filter chains and unobtrusively adding and removing filters from those chains. Filters are built around interfaces, and added or removed in a declarative manner by modifying the deployment descriptor for a Web application.

Base Filter Strategy: A base filter serves as a common superclass for all filters. Common features can be encapsulated in the base filter and shared among all filters. For example, a base filter is a good place to include default behavior for the container callback methods in the Declared Filter Strategy.

Template Filter Strategy: Using a base filter from which all others inherit allows the base class to provide template method [Gof] functionality. In this case, the base filter is used to dictate the general steps that every filter must complete, while leaving the specifics of how to complete that step to each filter subclass.

Typically, these would be coarsely defined, basic methods that simply impose a limited structure on each template. This strategy can be combined with any other filter strategy, as well.

Using Intercepting Filters centralizes control with loosely coupled handlers. Filters provide a central place for handling processing across multiple requests, as does a controller. Filters are better suited to massaging requests and responses for ultimate handling by a target resource, such as a controller. Additionally, a controller often ties together the management of numerous unrelated common services, such as authentication, logging, encryption, and so forth, while filtering allows for much more loosely coupled handlers, which can be combined in various combinations.

Intercepting filters improves reusability. Filters promote cleaner application partitioning and encourages reuse. These pluggable interceptors are transparently added or removed from existing code, and due to their standard interface, they work in any combination and are reusable for varying presentations.

Intercepting filters are declarative and have flexible configuration. Numerous services are combined in varying permutations without a single recompile of the core code base.

But using intercepting filters the information haring is inefficient. Sharing information between filters can be inefficient, since by definition each filter is loosely coupled. If large amounts of information must be shared between filters, then this approach may prove to be costly. J2EE DESIGN PATTERNS - Front Controller When the user access the view directly without going thought any centralized mechanism each view is required to provide its; own system services, often resulting in duplication of code and view navigations is left to the views, this may result in commingled view content and view navigation.

A centralized point of contact for handling a request may be useful, for example, to control and log a user's progress through the site. .

Introducing a controller as the initial point of contact for handling a request. The controller manages the handling of the request, including invoking security services such as authentication and authorization, delegating business processing, managing the choice of an appropriate view, handling errors, and managing the selection of content creation strategies.

The controller provides a centralized entry point that controls and manages Web request handling. By centralizing decision points and controls, the controller also helps reduce the amount of Java code, called scriptlets, embedded in the JavaServer Pages (JSP) page.

Centralizing control in the controller and reducing business logic in the view promotes code reuse across requests. It is a preferable approach to the alternative-embedding code in multiple views-because that approach may lead to a more error-prone, reuse-by-copy- and-paste environment.

Typically, a controller coordinates with a dispatcher component. Dispatchers are responsible for view management and navigation. Thus, a dispatcher chooses the next view for the user and vectors control to the resource. Dispatchers may be encapsulated within the controller directly or can be extracted into a separate component.

The responsibilities of the components participating in this patterns are :

Controller : The controller is the initial contact point for handling all requests in the system. The controller may delegate to a helper to complete authentication and authorization of a user or to initiate contact retrieval.

Dispatcher : A dispatcher is responsible for view management and navigation, managing the choice of the next view to present to the user, and providing the mechanism for vectoring control to this resource. A dispatcher can be encapsulated within a controller or can be a separate component working in coordination. The dispatcher provides either a static dispatching to the view or a more sophisticated dynamic dispatching mechanism. The dispatcher uses the RequestDispatcher object (supported in the servlet specification) and encapsulates some additional processing.

Helper : A helper is responsible for helping a view or controller complete its processing. Thus, helpers have numerous responsibilities, including gathering data required by the view and storing this intermediate model, in which case the helper is sometimes referred to as a value bean. Additionally, helpers may adapt this data model for use by the view. Helpers can service requests for data from the view by simply providing access to the raw data or by formatting the data as Web content. A view may work with any number of helpers, which are typically implemented as JavaBeans components (JSP 1.0+) and custom tags (JSP 1.1+). Additionally, a helper may represent a Command object, a delegate, or an

XSL Transformer, which is used in combination with a stylesheet to adapt and convert the model into the appropriate form.

View A view represents and displays information to the client. The view retrieves information from a model. Helpers support views by encapsulating and adapting the underlying data model for use in the display.

Front Controller centralizes control. A controller provides a central place to handle system services and business logic across multiple requests. A controller manages business logic processing and request handling. Centralized access to an application means that requests are easily tracked and logged. Keep in mind, though, that as control centralizes, it is possible to introduce a single point of failure. In practice, this rarely is a problem, though, since multiple controllers typically exist, either within a single server or in a cluster.

Front Controller improves manageability of security. A controller centralizes control, providing a choke point for illicit access attempts into the Web application. In addition, auditing a single entrance into the application requires fewer resources than distributing security checks across all pages.

Front Controller improves reusability. A controller promotes cleaner application partitioning and encourages reuse, as code that is common among components moves into a controller or is managed by a controller. J2EE DESIGN PATTERNS - Composite viewIn real world application web pages present content from numerous data sources, using multiple subviews that comprise a single display page. The web pages are built by embedding formatting code directly with each atomic view. Atomic portion of the view content changes frequently , modification to the layout of multiple view is difficult and error prone when subviews are directly embedded and duplicated in multiple views. Embedding frequently changing portions of template text directly into views also potentially affects the availability and administration of the system. The server may need to be restarted before clients see the modifications or updates to these template components.

The solution to this is to use composite views that are composed of multiple atomic subviews. Each component of the template may be included dynamically into the whole and the layout of the page may be managed independently of the content.

This solution provides for the creation of a composite view based on the inclusion and substitution of modular dynamic and static template fragments. It promotes the reuse of atomic portions of the view by encouraging modular design. It is appropriate to use a composite view to generate pages containing display components that may be combined in a variety of ways. The layout of the page is managed and modified independent of the subview content.

Another benefit of this pattern is that Web designers can prototype the layout of a site, plugging static content into each of the template regions. As site development progresses, the actual content is substituted for these placeholders.

The responsibilities of the components participating in this patterns are :

Composite View : A composite view is a view that is an aggregate of multiple subviews.

View Manager : The View Manager manages the inclusion of portions of template fragments into the composite view. The View Manager may be part of a standard JSP page runtime engine, in the form of the standard JavaServer Pages (JSP page) pages include tag (<jsp:include>), or it may be encapsulated in a JavaBean helper (JSP page 1.0+) or custom tag helper (JSP page 1.1+) to provide more robust functionality. A benefit of using a mechanism other than the standard include tag is that conditional inclusion is easily done. For example, certain template fragments may be included only if the user fulfills a particular role or certain system conditions are satisfied. Furthermore, using a helper component as a View Manager allows for more sophisticated control of the page structure as a whole, which is useful for creating reusable page layouts.

Included View An included view is a subview that is one atomic piece of a larger whole view. This included view could also potentially be a composite, itself including multiple subviews.

Composite view improves modularity and reuse. The pattern promotes modular design. It is possible to reuse atomic portions of a template, such as a table of stock quotes, in numerous views and to decorate these reused portions with different information. This pattern permits the table to be moved into its own module and simply included where necessary. This type of dynamic layout and composition reduces duplication, fosters reuse, and improves maintainability.

Composite view enhances flexibility. A sophisticated implementation may conditionally include view template fragments based on runtime decisions, such as user role or security policy.

Composite view enhances maintainability and manageability. It is much more efficient to manage changes to portions of a template when the template is not hardcoded directly into the view markup. When kept separate from the view, it is possible to modify modular portions of template content independent of the template layout. Additionally, these changes are available to the client immediately, depending on the implementation strategy. Modifications to the layout of a page are more easily managed as well, since changes are centralized.

Composite view reduces manageability. Aggregating atomic pieces of the display together to create a single view introduces the potential for display errors, since subviews are page fragments. This is a limitation that can become a manageability issue. For example, if a JSP page page is generating an HTML page using a main page that includes three subviews, and the subviews each include the HTML open and close tag (that is, <HTML> and </HTML>), then the composed page will be invalid. Thus, it is important when using this pattern to be aware that subviews must not be complete views. Tag usage must be accounted for quite strictly in order to create valid composite views, and this can become a manageability issue.

But Composite view has performance impact. Generating a display that includes numerous subviews may slow performance. Runtime inclusion of subviews will result in a delay each time the page is served to the client. In an environment with strict Service Level Agreements that mandate specific response times, such performance slowdowns, though typically extremely minimal, may not be acceptable. An alternative is to move the subview inclusion to translation time, though this limits the subview to changing when the page is retranslated. J2EE DESIGN PATTERNS - Data Access Object The client tier in an EJB system needs a way to transfer bulk data with the server, as the J2EE aplications implement server side business component.Some methods exposed by the business components return data to the client. Often, the client invokes a business object's get methods multiple times until it obtains all the attribute values.

If the client needs to display or update a set of attributes that live on the server, these attributes could live in an entity bean or be accessible through a session bean. The client could get or update the data is by loading many parameters into a method call, when updating data on the server, or by making multiple fine-grained calls to the server to retrieve data. Every call between the client and server is a remote method call with substantial network overhead. If the client application calls the individual getter and setter methods that require or update single attribute values, it will require as many remote calls as there

are attributes. The individual calls generate a lot of network traffic and affects severely the system performance.

The solution to this problem is to use a plain java classes called Value Objects or Transfer Objects which encapsulate the bulk business data. A single method call is used to send and retrieve the Transfer Object / Value Obects. When the client requests the enterprise bean for the business data, the enterprise bean can construct the Transfer Object, populate it with its attribute values, and pass it by value to the client.

When an enterprise bean uses a Transfer Object / Value Obects, the client makes a single remote method invocation to the enterprise bean to request the Transfer Object / Value Obects instead of numerous remote method calls to get individual attribute values. The enterprise bean then constructs a new Transfer Object instance, copies values into the object and returns it to the client. The client receives the Transfer Object / Value Obects and can then invoke accessor or getter methods on the Transfer Object to get the individual attribute values from the Transfer Object. The implementation of the Transfer Object / Value Obectsmay be such that it makes all attributes public. Because the Transfer Object / Value Obects is passed by value to the client, all calls to the Transfer Object / Value Obects instance are local calls instead of remote method invocations.

A Transfer object / value object is a plain serializable Java class that represents a snapshot of some server side data, as in the following code example: import java.io.Serializable;

public class OneValueObject implements Serializable {

private int attribute1; private String attribute2; private String attribute3; private long attribute4;

public int getAttribute1();

public String getAttribute2(); public String getAttribute3(); public long getAttribute4(); }//OneValueObject

The responsibilities of the three components participating in this patterns are :

Client This represents the client of the enterprise bean. The client can be an end-user application, like jsp, servlets or a java applet, as in the case of a rich client application that has been designed to directly access the enterprise beans. The client can be Business Delegates or a different BusinessObject.

Business Object The Business Object represents a role in this pattern that can be fulfilled by a session bean, an entity bean, or a Data Access Object (DAO). The BusinessObject is responsible for creating the Transfer Object and returning it to the client upon request. The Business Object may also receive data from the client in the form of a Transfer Object / Value Obects and use that data to perform an update.

Transfer Object / Value Objects The Transfer Object / Value Obects is an arbitrary serializable Java object referred to as a Transfer Object / Value Obects. Transfer Object / Value Obects has all the business values required by the client. A Transfer Object / Value Obects class may provide a constructor that accepts all the required attributes to create the Transfer Object / Value Obects. The constructor may accept all entity bean attribute values that the Transfer Object / Value Obects is designed to hold. Typically, the members in the Transfer Object / Value Obects are defined as public, thus eliminating the need for get and set methods. If some protection is necessary, then the members could be defined as protected or private, and methods are provided to get the values. Transfer Objects / Value Obects can be mutable or immutabel depending on whether the application wants to allow updates to the Transfer Objects / Value Obects J2EE DESIGN PATTERNS - Transfer Object / Value Object

The client tier in an EJB system needs a way to transfer bulk data with the server, as the J2EE aplications implement server side business component.Some methods exposed by the business components return data to the client. Often, the client invokes a business object's get methods multiple times until it obtains all the attribute values.

If the client needs to display or update a set of attributes that live on the server, these attributes could live in an entity bean or be accessible through a session bean. The client could get or update the data is by loading many parameters into a method call, when updating data on the server, or by making multiple fine-grained calls to the server to retrieve data. Every call between the client and server is a remote method call with substantial network overhead. If the client application calls the individual getter and setter methods that require or update single attribute values, it will require as many remote calls as there are attributes. The individual calls generate a lot of network traffic and affects severely the system performance.

The solution to this problem is to use a plain java classes called Value Objects or Transfer Objects which encapsulate the bulk business data. A single method call is used to send and retrieve the Transfer Object / Value Obects. When the client requests the enterprise bean for the business data, the enterprise bean can construct the Transfer Object, populate it with its attribute values, and pass it by value to the client.

When an enterprise bean uses a Transfer Object / Value Obects, the client makes a single remote method invocation to the enterprise bean to request the Transfer Object / Value Obects instead of numerous remote method calls to get individual attribute values. The enterprise bean then constructs a new Transfer Object instance, copies values into the object and returns it to the client. The client receives the Transfer Object / Value Obects and can then invoke accessor or getter methods on the Transfer Object to get the individual attribute values from the Transfer Object. The implementation of the Transfer Object / Value Obectsmay be such that it makes all attributes public. Because the Transfer Object / Value Obects is passed by value to the client, all calls to the Transfer Object / Value Obects instance are local calls instead of remote method invocations.

A Transfer object / value object is a plain serializable Java class that represents a snapshot of some server side data, as in the following code example: import java.io.Serializable;

public class OneValueObject implements Serializable {

private int attribute1; private String attribute2; private String attribute3; private long attribute4;

public int getAttribute1(); public String getAttribute2(); public String getAttribute3(); public long getAttribute4(); }//OneValueObject

The responsibilities of the three components participating in this patterns are :

Client This represents the client of the enterprise bean. The client can be an end-user application, like jsp, servlets or a java applet, as in the case of a rich client application that has been designed to directly access the enterprise beans. The client can be Business Delegates or a different BusinessObject.

Business Object The Business Object represents a role in this pattern that can be fulfilled by a session bean, an entity bean, or a Data Access Object (DAO). The BusinessObject is responsible for creating the Transfer Object and returning it to the client upon request. The Business Object may also receive data from the client in the form of a Transfer Object / Value Obects and use that data to perform an update.

Transfer Object / Value Objects The Transfer Object / Value Obects is an arbitrary serializable Java object referred to as a Transfer Object / Value Obects. Transfer Object / Value Obects has all the business values required by the client. A Transfer Object / Value Obects class may provide a constructor that accepts all the required attributes to create the Transfer Object / Value Obects. The constructor may accept all entity bean attribute values that the Transfer Object / Value Obects is designed to hold. Typically, the members in the Transfer Object / Value Obects are defined as public, thus eliminating the need for get and set methods. If some protection is necessary, then the members could be defined as protected or private, and methods are provided to get the values. Transfer Objects / Value Obects can be mutable or immutabel depending on whether the application wants to allow updates to the Transfer Objects / Value Obects

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy