« JUnit 4.0 Design Madness | Main | Comparing SDO with DAO »

Scripting with SDO

One of the nice things about SDO is that the dynamic DataObject API provides an ideal way of passing structured data into rendering engines or JSP pages. It also enables much easier scripting of database driven web apps with ease of use to rival, if not better, scripting languages such as PHP.

Here’s an example of a JSP page to display the contents of a particular table:

<%@ include file="header.jsp"%>

<h1>Customers</h1>

<table border="1">
<tr>
<td>Customer Name</td>
<td>Country</td>
<td>Licenses</td>
</tr>

<%
// get a list of customer objects
List list = das.getTableRows( "customer", "1=1" );

// iterate through the list
Iterator iter = list.iterator();
while (iter.hasNext()) {
DataObject customer = (DataObject) iter.next();
%>

<tr>
<td><%= customer.getString( "name") %></td>
<td><%= customer.getString( "country") %></td>
<td><%= customer.getString( "licenses") %></td>
</tr>

<%
}
%>

</table>

<%@ include file="footer.jsp"%>

In this example, the header.jsp contains some basic layout and the necessary Java imports and code to initialise the data access service (the ‘das’ variable).

The beauty of this approach compared to using JDBC directly, apart from the drastic reduction in source code, is the fact that there is no need to manage connections or close our resources. Also, the DataObject can be stored in a session, modified in subsequent pages and then can be passed back into the DAS to update the database.

Here’s a JSP scriptlet to perform an update (this would likely be in a page which is the target action of an HTML form).

<%
DataObject customer = (DataObject) request.getSession().getAttribute("customer");

customer.setString( "name”, request.getParameter("name") );
customer.setString( "country”, request.getParameter("country”) );
customer.setString( "licenses”, request.getParameter("licenses") );

das.applyChanges( customer );
%>

For enterprise web applications using servlets and/or a web framework such as Struts or Spring MVC, much of this code would be encapsulated in action classes but the SDO DataObject can still be used as a convenient way of passing data to a JSP page for rendering.

Comments

Very good suggestion for implementing this DAS

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)