Recipe10.1.Accessing JDBC Data Sources from an Action


Recipe 10.1. Accessing JDBC Data Sources from an Action

Problem

You want to access a data source directly from a Struts Action.

Solution

Don't do it! Only access the data source from within your application's model.

Discussion

Though Struts is referred to as an MVC framework for web applications, Struts doesn't attempt to provide the model of that paradigm. Struts provides only the bridge between the view and the model, Struts Actions. An Action shouldn't access the database; an Action shouldn't need to know how the data is stored and accessed. Instead, an Action acts as a thin façade to your business services, marshalling data from the view to the model and back. The following FAQ from the Struts web site puts it quite succinctly:

Ideally, all the database access code should be encapsulated behind the business API classes, so Struts doesn't know what persistence layer you are using (or even if there is a persistence layer). It passes a key or search String and gets back a bean or collection of beans. This lets you use the same business API classes in other environments, and lets you run unit tests against your business API outside of Struts or a HTTP environment.

While Struts does support the data-source element for configuring JDBC data sources, the Struts release notes state that this element may not be supported in the future. According to the Struts documentation, you should use the data-source element when you need to pass a javax.sql.DataSource to a legacy API. This results in a dependency between the Action and the persistence layer as illustrated in Figure 10-1.

Figure 10-1. Data source access by an Action


A better approach in this situation is to create a façade around the legacy API. The façade provides a data-independent implementation of the legacy API. Internally, the façade is responsible for acquiring the required data source and delegating calls to the legacy service, passing the data source as needed. Your Actions can interact with the façade without needing to be bound to the persistence details. This (better) model is shown in Figure 10-2.

Figure 10-2. Data source by a service façade


The façade-based architecture results in a more flexible system that can adapt from low-level changes to legacy systems without requiring you to rewrite your Actions.

See Also

The Struts FAQ on database-related issues can be found at http://struts.apache.org/faqs/database.html. For more information on accessing databases, see Java Database Best Practices by George Reese (O'Reilly).



    Jakarta Struts Cookbook
    Jakarta Struts Cookbook
    ISBN: 059600771X
    EAN: 2147483647
    Year: 2005
    Pages: 200

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net