Base on the previous post, I have used the struts-config.xml to define the datasource to access to the MySQL database. The datasource class is code within the Action class (controller layer) and map to the struts-config.xml.
In order to improve the programming pratice, the datasource can be created via JNDI and the java code should be sit within the model layer. As a result, business logic will separate from the controller layer and making the Action class without knowing any relation with business class at all.
I am using Apache Tomcat 5.x and so, I will define the datasource resource via JNDI within the context.xml.
<Context path=”/bookstore”>
<ResourceLink global=”jdbc/bookstoreDB” name=”jdbc/bookstoreDB” type=”javax.sql.DataSource”/>
</Context>
The java code to make the database connection accessing the JNDI would be look like this:
Connection cn(){
DataSource ds = null;
try {
Context ctx = new InitialContext();
if ( ctx == null ) {
throw new RuntimeException(“JNDI Context could not be found.”);
}
ds = (DataSource)ctx.lookup(“java:comp/env/jdbc/bookstorDB”);
if ( ds == null ) {
throw new RuntimeException(“DataSource could not be found.”);
}
return ds.getConnection();
// Handle any JNDI errors
} catch (NamingException ne) {
throw new RuntimeException(“A JNDI error occured. ” + ne.getMessage());
}catch(Exception e){
System.err.println(“Boom – No Context”);
}
return null;
}
Alternative, you can use JSP Standard Tag Library (JSTL) without embedding any Java code. I am using JSTL SQL tag here and may look like this:
<%@ taglib prefix=”sql” uri=”http://java.sun.com/jsp/jstl/sql” %>
<%@ taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core” %>
<sql:setDataSource dataSource=”jdbc/bookstoreDB” />
<sql:query var=”qryBooks” >
SELECT bookID, bookTitle, bookAuthor, bookPublisher FROM book
</sql:query>
<table>
<c:forEach var=”row” items=”${qryBooks.rows}”>
<tr>
<td>${row.bookID}</td>
<td>${row.bookTitle}</td>
<td>${row.bookAuthor}</td>
<td>${row.bookPublisher}</td>
</tr>
</c:forEach>
</table>