File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Accessing context params from an Action class

 
ernest fakudze
Ranch Hand
Posts: 216
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Tiago Fernandez
Ranch Hand
Posts: 167
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
ernest fakudze
Ranch Hand
Posts: 216
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 167
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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");
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic