This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
i am doing struts application where i creating customized Action servlet by extending RequestProcessor. I want to access the list of countries from datbase and make them avaliable to every entry form. I am using DBCP. HOw to get Database connection in Customized Action servlet before client makes first request and make them avaliable to every enrey form
I'd suggest you do this by creating a class that implements the org.apache.struts.action.Plugin interface and putting your code in the init() method. You would then register the plugin in your struts-config.xml file just as you would the validator plugin or any other plugin. If you do this, your code will run when the Struts ActionServlet initializes.
In your code, I would first get the datasource with the following code:
Once you have the collection, I'd suggest putting it in application context so that it is available to all other Action classes and JSPs.
Warning: The DBCP has been deprecated and is no longer availble in version 1.3.5 of Struts. It might be a good idea to get away from DBCP and move to a DataSource stored in JNDI. [ February 01, 2007: Message edited by: Merrill Higginson ]
One of the first things the Struts ActionServlet does when it initializes is to read the struts-config.xml file. It then follows the instructions in the config file and creates objects as needed. If you've specified a DataSource in your config file, the ActionServlet will create it and put it in Application scope. After it is finished with all its configuration tasks, the ActionServlet will call the init method on any plugin classes that are registered in the config file. So, by the time it calls your init method, everything has been initialized.
In answer to your second question: Java Naming and Directory Interfact (JNDI) is a part of the J2EE specification and is supported by every application server. It's considered best practice to register a DataSource in JNDI. Each application server has its own interface for setting up JNDI Datasources. Search for JNDI or DataSource in your App server's documentation and you'll find it.