Home > Eclipse, Java, JBoss, Maven, MySql > Accessing databases using datasource xml

Accessing databases using datasource xml

We will use the previous struts project to setup database access to MySQL running on localhost.
Run the following command to create the .project and .classpath files for Eclipse and import the project in Eclipse

mvn eclipse:m2eclipse

Download the database driver mysql-connector-java-5.1.11-bin.jar from here and save it to the lib folder in this location $JBOSS_HOME/server/web/lib

Create a jboss-web.xml file in the WEB-INF folder with the following content

<?xml version="1.0" encoding="UTF-8"?>

In the web.xml file add the following :


Create a datasource xml file and add it to the deploy dir of JBoss.

Here is the content of my file:

 <!-- Typemapping for JBoss 4.0 -->

Replace database-name, username and password with appropriate values.

To keep things simple to test, we will add an action in struts-config and have the Action class call the database.

In the action class add this

private final String DATABASE_JNDI_SOURCE = "java:CodesiloDS";

and have this in the execute method. (In the real world most of this code would reside in your model and any helper classes.)

public ActionForward execute(ActionMapping mapping, ActionForm form,
 HttpServletRequest request, HttpServletResponse response)
 throws Exception {

 Connection conn = null;
 Statement stmt = null;
 ResultSet rs = null;
 String date ="";
 Context ctx = new InitialContext();
 DataSource ds = (DataSource)ctx.lookup(DATABASE_JNDI_SOURCE);
 if(ds!= null){
 conn = ds.getConnection();
 stmt = conn.createStatement();
 rs = stmt.executeQuery("select curdate() from dual;");
 date = rs.getString(1);
 catch(Exception e){
 ---- code here----
 catch(Exception e){
 ---- code here -----
 System.out.println("This is a test: " + date);
 return mapping.findForward("success");

Once we call the action, we should see the current date printed on the console.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: