简体   繁体   中英

DAO Design Pattern and Servlets

I am reading about the DAO design pattern on Oracle's website and I'm trying to understand the below image in the context of using JSP's, Servlets, plain java objects, and the MVC pattern. In my case would the BusinessObject be my servlet and the TransferObject be my java class with only properties, mutators, and accessors (DTO)?

For example, if I had this code in a servlet (controller)

DTO.setFirstName(request.getParameter("firstName"));
DTO.setLastName(request.getParameter("lastName"));
DAO.save(DTO);


(source: sun.com )

Almost. Between the controller, which handles presentation logic, and the DAO, which handles Data access logic, there should be a business layer, containing the business objects.

The main responsibilities of these business objects are

  • to provide business services to the controllers. They are a facade
  • to encapsulate the business logic of the application
  • to demarcate transacations
  • to use one or several DAOs to get, find and persist objects.

This layer is very important because you want to be able to perform several operations on your database within a single transaction. And it should not be the responsibility of the web controller to handle this. Moreover, the same business services could be used by other clients than the web controllers (Swing client, batch, etc.)

Business objects are typically implemented using session EJBs, or Spring services.

They're also useful to be able to

  • unit test the controller by mocking the business objects
  • unit test the business logic by mocking the DAOs

是的,BusinessObject看起来像MVC的C(控制器)。

The whole DAO pattern is part of the Model layer in MVC, in which the BussinessObject offers the Model interface and the DAO and DTO objects part of the pattern implementation.

Your servlet would be (in) the Controller layer and the class that you use to render the HTML (or other format) to be sent to the client would be (in) the View layer.

The size and complexity of your web application determines wether the layers can be built from just one class or not.

In answer to your coment, the DTO (we call it data-holder objects) only consist of attributes, getters/setters, cleanup and validation methods. They function as a separation of concerns between storage / transfer and the implementation of bussiness logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM