Section 3.5. Adding a DAO


3.5. Adding a DAO

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 abstractionit hides the actual persistence specifics behind a common interface.

The DAO we create in this chapter still stores the DTO objects in a simple ArrayList. 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.

The CarDAO provides a findAll( ) method that returns a List of CarDTOs. 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 the ControllerServlet 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 reuseyour 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.



JBoss at Work. A Practical Guide
JBoss at Work: A Practical Guide
ISBN: 0596007345
EAN: 2147483647
Year: 2004
Pages: 197

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net