Completing an EAR - Adding a DAO
(Page 3 of 4 )
In that spirit, let’s add another component that will pay dividends in future flexibility. Right now, your servlet is creating the car list each time a request comes in. This really isn’t optimal. Servlets should deal with the mechanics of the HTTP request/response cycle. They shouldn’t perform persistence tier tasks.
We aren’t quite ready to install a database (that happens in the next chapter), but we can lay the groundwork by creating a Data Access Object (DAO). A DAO is a layer of abstraction—it hides the actual persistence specifics behind a common interface.
The DAO we create in this chapter still stores the DTO objects in a simpleArrayList. In the next chapter, the DAO will pull car data from a database that uses JDBC. In the chapter after that, it will use Hibernate (an Object/Relational Mapper) to do the same thing. By getting the DAO in place now, however, we’ll be able to make these implementation changes without affecting presentation-tier code. Loose coupling and high cohesion comes to the rescue again.
TheCarDAOprovides afindAll()method that returns aListofCarDTOs. The source code in Example 3-7 can be found in the common directory in ch03b-dao.
Example 3-7. CarDAO.java
package com.jbossatwork.dao;
import java.util.*;
import com.jbossatwork.dto.CarDTO;
public class CarDAO
{
private List carList;
public CarDAO()
{
carList = new ArrayList();
carList.add(new CarDTO("Toyota", "Camry", "2005"));
carList.add(new CarDTO("Toyota", "Corolla", "1999"));
carList.add(new CarDTO("Ford", "Explorer", "2005"));
}
public List findAll()
{
return carList;
}
}
The corresponding change in theControllerServlet calls the newly created DAO in Example 3-8.
Example 3-8. ControllerServlet.java
// perform action
if(VIEW_CAR_LIST_ACTION.equals(actionName))
{
CarDAO carDAO = new CarDAO();
request.setAttribute("carList", carDAO.findAll());
destinationPage = "/carList.jsp";
}
Not only does this change simplify the code in the servlet, it feels more correct as well. The servlet concerns itself solely with web mechanics and delegates the database tasks to a dedicated class. Another pleasant side effect of this is reuse—your data access code can now be called outside of the web tier. If a business tier object needs access to this data, it can make the same call that we make.
Build and deploy the code to verify that we haven’t broken your application with this change.
Next: Using XDoclet >>
More Web Authoring Articles
More By O'Reilly Media
|
This article is excerpted from chapter three of the book JBoss at Work: A Practical Guide, written by Tom Marrs and Scott Davis (O'Reilly; ISBN: 0596007345). Check it out today at your favorite bookstore. Buy this book now.
|
|