| Author |
Accessing context params from an Action class
|
ernest fakudze
Ranch Hand
Joined: Aug 27, 2001
Posts: 216
|
|
Hello there, Problem: I'm trying to do a simple logon app using Struts. I have specified the database connection details (dbURL, username, pwd) in the web-xml file as context params for scalability reasons?? My LogonAction class is a Struts Action object e.g. extends org.apache.action.Action. How do I access the db details in the Action class? Am I doing it the right way or do I need to re-design the app?
|
In a time of drastic change it is the learners who inherit the future. The learned usually find themselves equipped to live in a world that no longer exists.<br />Eric Hoffer
|
 |
Tiago Fernandez
Ranch Hand
Joined: May 16, 2003
Posts: 167
|
|
Ernest, If I got ya, you don't have to re-design your app, but I recommend that your data-source should be configured in the struts-config.xml file, instead web.xml. With the pre-configured data-source from struts-config.xml, just use the following sample code in your LogonAction class: struts-config.xml: ... <data-sources> <data-source> <set-property property="driverClass" value="org.gjt.mm.mysql.Driver" /> <set-property property="url" value="jdbc:mysql://localhost/tiago" /> <set-property property="maxCount" value="5"/> <set-property property="minCount" value="1"/> <set-property property="user" value="root"/> </data-source> </data-sources> ... LogonAction.java: public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { javax.sql.DataSource dataSource; java.sql.Connection myConnection; ... try { dataSource = servlet.findDataSource(null); myConnection = dataSource.getConnection(); } catch (SQLException sqle) { getServlet().log("Connection.process", sqle); } finally { try { myConnection.close(); } catch (SQLException e) { getServlet().log("Connection.close", e); } } } } That's it! Please correct me if I'm wrong... I'm just a greenhorn yet
|
Tiago Fernandez
http://www.tiago182.spyw.com/
|
 |
ernest fakudze
Ranch Hand
Joined: Aug 27, 2001
Posts: 216
|
|
|
Thanks very much for the insight Tiago. I believe this is exactly what I need to do. You are the man. Cheers!!
|
 |
Tiago Fernandez
Ranch Hand
Joined: May 16, 2003
Posts: 167
|
|
Thanks dude! Hey, I figured out that the method to get the data source "servlet.findDataSource()" is deprecated. Instead, use the followin': DataSource dataSource =(DataSource) servlet.getServletContext().getAttribute("DATA_KEY_CONFIGURED_IN_STRUTS-CONFIG.XML");
|
 |
 |
|
|
subject: Accessing context params from an Action class
|
|
|