J2EE/Struts 1.1 pattern tips

Wai Tak Pau

Greenhorn

Posts: 4

posted 13 years ago

I'm trying to seperate database calls from my actions and I have that implementation seperate in a class called DataAccess. Now I'm trying to think of what the best way of architecting this would be. I want to make use of the getDataSource() method of my Action class but I don't want my Action class making db calls and I don't want my DataAccess class extending the Action class. How would I set up this relationship between my action class and my class that manages all database calls? The way I have it set up right now is that the Action class creates a new instance of a connection (using getDataSource()) and then passes that as an argument into a newly created instance of my DataAccess Object which my DataAccess object can then use to make db calls. This doesn't seem right though. The functionality for connecting and communicating with the database should be encapsulated completely in my DataAccess object right? I'm looking through the J2EEpatterns at sun but nothing specific toStruts 1.1. The data access tutorial at apache shows an example of an action class making a database connection in an actual Action which is not what I want to do. If anyone could provide some tips or examples I'd appreciate it. Thanks in advance.

Peter den Haan

author
Ranch Hand

Posts: 3252

posted 13 years ago

There is no clean way to do this using Struts infrastructure. You are right: passing in the DataSource from your Action is not good. The Action should not need to care what persistence mechanism is used by the DAO. Alternatively, since the DataSource gets stored into the servlet context (application scope) your DAO could conceivably retrieve it directly from there, but this introduces an unnecessary and ugly dependence of your DAO classes on the servlet API. Not very good either. There is a standard J2EE way to solve this problem, however, and this is to get your application server to set up a DataSource for you in JNDI and for your DAO class to retrieve it from there. This will work in all application servers, in both the web and EJB tiers. This article describes in detail how to do this for Tomcat 4; other application servers work in similar ways. Struts' DataSource support has essentially long been superseded by the J2EE way of doing things -- avoid it if you can. - Peter