|
Recipe 10.1. Accessing JDBC Data Sources from an ActionProblemYou want to access a data source directly from a Struts Action. SolutionDon't do it! Only access the data source from within your application's model. DiscussionThough 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:
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 ActionA 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çadeThe 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 AlsoThe 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). |
|