wood burning stoves 2.0*
The moose likes OO, Patterns, UML and Refactoring and the fly likes Front controller and DAO, design question! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "Front controller and DAO, design question!" Watch "Front controller and DAO, design question!" New topic
Author

Front controller and DAO, design question!

Joel Hutters
Greenhorn

Joined: Sep 07, 2006
Posts: 21
Hey!
I'm developing a web-application and I'm using the front controller pattern for simplified request handling and the DAO pattern for a unified data access.
What part of the web-app shall use the DAO pattern?

I had this code in my Command objects from the beginning and it looked something like this...

CustomerAction.java
[CODE]
public class CustomerCommand implements Command {
public String execute(HttpServletRequest req, HttpServletResponse resp) {
String view = "example.jsp"
[ November 12, 2006: Message edited by: Joel Hutters ]
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
There are a few domains of knowledge here ... HTTP (session, request, response, etc), JDBC (connections, resultsets, etc) and business. Let's try to keep them separate.

As a first cut, let's restrict HTTP knowledge to the controller and the commands. Make the command's job three things: Get input parameters from the request, call some business stuff, put results back on the request so the output page can use them. The business should not import any javax.servlet classes.

Let's put the business stuff in a POJO. For a simple CRUD app its job is to use its input variables, talk to some data accessors and return some stuff. In a more complex app it might access several data sources, do some computation, apply complex rules, etc.

The DAO knows how to connect to the database, do a query or update, return the results. Let's keep all JDBC knowledge in the data accessor so the business layer doesn't import any java.sql classes. The data accessor has to translate all database things into generic things. Imagine trying to change a data acessor from a database source to a remote web service call source, or a JMS source. Keep its interface very generic.

Does that make sense so far? It's possible to keep HTTP out of the commands, but I'm not sure whether it's worth the effort just yet. What do you think?


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joel Hutters
Greenhorn

Joined: Sep 07, 2006
Posts: 21
Very good explanation, and it sounds to be a good way to go. I guess it doesn't matter if my Command objects are http-specific, as long as I keep them clean and simple.

Something like this might work? With no http-related stuff...


Then regarding complicated things like form-validation. What about having that here as well? Like a validation method the checks the state of the pojo, new word for me, but I like it To keep the code simple I might have a validation helper or something like that?


The DAO knows how to connect to the database, do a query or update, return the results. Let's keep all JDBC knowledge in the data accessor so the business layer doesn't import any java.sql classes. The data accessor has to translate all database things into generic things. Imagine trying to change a data acessor from a database source to a remote web service call source, or a JMS source. Keep its interface very generic.

As it is know I have:
DAOFactory (abstract) -> which create concrete factories like MysqlFactory ect
I can get DAO objects like CustomerDAO, UserDAO etc with help of my concrete DAOFactories. These are interfaces, so they all if implementations like MysqlCustomerDAO. Maybe not very generic but I guess I need to use an OR-mapper to achieve this? Anyway, the important thing is that my business layer communicates with my Data Access layer through a common interface no matter what DBMS.

As it's now I pass value-objects (or is it called transport objects?) from my business layer to the DAO, and the other way around.

Any thoughts?

[ October 25, 2006: Message edited by: Joel Hutters ]
[ October 25, 2006: Message edited by: Joel Hutters ]
Peer Reynders
Bartender

Joined: Aug 19, 2005
Posts: 2906
Right now it looks like you haven't quite made up your mind whether your Customer Class is a Data Transfer Object (PEAA) or an Active Record. The presence of the following methods would indicate that your Customer Class is an Active Record:

On the other hand with the canonical use of the DAO you would not find the CRUD methods on the DTO or even the Business Object (that may be created from the DTO). On a distributed system you would pass the DTO, on a co-located system you would pass the Business Object to and from the DAO for the CRUD operations.

BTW: Careful with the term "Value Object".
See: Differences between Value Object und Transfer Object)

POJO


"Don't succumb to the false authority of a tool or model. There is no substitute for thinking."
Andy Hunt, Pragmatic Thinking & Learning: Refactor Your Wetware p.41
Joel Hutters
Greenhorn

Joined: Sep 07, 2006
Posts: 21
As I have it now in my application I have transfer object like this, ok now

No CRUID-methods. But when reading Stan James, and from my own thoughts, it's not a good way to make the calls from my "http-specific" command object to my DAO. I'm confused here, and don't really get the pieces together. Would you, or anyone else like to illustrate an example, simple code or explanation of how to do it "right"?

I would appreciate that very much
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
I use a (purchased) front controller framework that takes interesting stuff from the request and builds an XML DOM. The command gets XML DOM in and returns XML DOM out. The controller makes the output DOM available to the next JSP which uses a custom taglib that knows how to read the XML DOM. Lots of extra processing so I wouldn't recommend this, but it shows how they took care of the HTTP stuff in a single common front controller. Struts turns request parameters and such into Form objects, I think - never really used it. Anyhow, I'd look for the command to have simple inputs & outputs, no getters & setters. Here's one that does know about HTTP ...

Now I can have one controller that can call any new command. The controller examines the incoming request for some kind of key that lets it look up the command and the jsp that should get the output. Does that make sense?
Joel Hutters
Greenhorn

Joined: Sep 07, 2006
Posts: 21
Yeah it makes some sense but I'm still wondering a little bit about the POJO. Let's I have a Customer DTO like this one (described before):

Is it then POJO's task to "wrap" the calls to the DAO, and maybe perform some business logic after or before if necessary? How do I organize this stuff, packages and naming conventions etc? Is it a good choice to name it CustomerPOJO, and maybe have it in a package like com.appname.pojo?
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
In a stateless web server it's tempting to build a POJO for each query or update the user can do, or maybe one per page, sometimes called a Transaction Script. This is usually called an "anti-pattern", thoroughly procedural and not very object oriented. In fact it brings mainframe CICS COBOL designs back to mind. Now in my mind that's not a totally unpleasant memory - it worked like crazy and many aspects of web apps are startlingly similar to CICS.

In my current world, we followed a vendor design (avoiding responsbility here) with "services" that bring together a number of operations around a business entity or process. So we have a ContractService that does a lot of contract related stuff, a CaseService, a WorkflowService, etc. These have worked out well, but in a stateless server they are still pretty procedural. I would probably do this again rather than individual transaction scripts.

Packages per layer sounds good. Maybe something like

Sub packages per business functional area or domain area might be good, too. Like the contract, case, worfklow stuff I mentioned before.

In a tool like Eclipse, you might even play with putting these in separate projects so you can track dependencies through the BuiltPath properties. In that package list, core imports from nobody, everybody else imports from core and the package immediately below only.
Joel Hutters
Greenhorn

Joined: Sep 07, 2006
Posts: 21
Thanks for taking time and answering my questions. I think I've got it now, but what about form validation. Feels temptating to put validation logic in my pojos, what do you think about that?
[ October 27, 2006: Message edited by: Joel Hutters ]
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Yup, that sounds fine. In my world we have services that are called by browser clients via the controller & commands, by web service clients via XML/HTTP, by JMS clients with XML over MOM. In all cases the business service is the last line of defense for our processes and data. Services don't trust the clients for data correctness, authorization or anything else; they enforce the rules.

It can enhance your user experience to duplicate validation on the client, but you take on all the normal risks and problems with duplication of logic.

There are some tools that can make your validation more declarative for fewer lines of Java. One validator was once part of Struts but is now standalone. I don't have much hands on experience with that one, but it seemed to be more effort than just coding my own validation.
Joel Hutters
Greenhorn

Joined: Sep 07, 2006
Posts: 21
I'm very grateful for your answers Stan James, and I have started to reorganize things in my application now. I still have one questions though. I have a command class that collects request parameters from a web form that adds a new post to my blog. It looks something like this:

The last part sets request attributes, so that the view can redisplay the form, if the validation failed. My question is, considering the layer dependency rules, is it okay to use my DTO here?

Instead of doing this in my command class...

I could do this...

In this example, it's only about two attributes, but for an object with a lot of properties it would save alot of typing. Instead of making several request attributes available for my jsp-page, I could "drop" an entire DTO. But it's maybe a bad practice to create DTO:s if they contain invalid data? When I retrieve data from my data source, I simply set my request attributes with dto:s in my command classes so they view easily can display the data. But this feels like another case, since this is valid data... hmmm

Another example from the code posted above. When I call the create method of the BlogEntryService from my command class I do it like this:

What about doing like this?


Hope you understand what I mean, if you don't please let me know and I'll try to clarify it.

[ October 31, 2006: Message edited by: Joel Hutters ]
[ October 31, 2006: Message edited by: Joel Hutters ]
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
The "T" is key in DTO. These are pretty dumb structs that we use to Transfer data between layers that have some expensive or non-object protocol, say from a Servlet container to an EJB container. Since you're making direct calls, your service doesn't have to use DTOs. It can return rich business objects with real methods and behaviors. The three parameter constructor is fine, too. No need for a DTO parameter.

Next you need to get data from the command to the JSP. It's possible to pass the business objects over and make the JSP dig out the data it needs. It's also fairly common for the command to build up a JavaBean custom made with exactly the data that the JSP needs, no more, no less. If you buy into the sales hype that your JSP developer can be an HTML artist with some tag skills and no Java skills, they can use the Bean with ease. Anybody know a name for this, um, is it a real pattern? Do either of those options sound good?
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
Next you need to get data from the command to the JSP. It's possible to pass the business objects over and make the JSP dig out the data it needs. It's also fairly common for the command to build up a JavaBean custom made with exactly the data that the JSP needs, no more, no less.

Or, if you don't fancy introducing yet another boring data-holder class with no behaviour into your codebase, you could always pass information from the command to the JSP in a standard, generic object such as a Map.

I've done this successfully using either a separate "helper" method which takes a domain object and returns a fresh map filled with named values, or adding a method (maybe named something like "toMap", to fit in with the standard "toString") to the domain object which returns such a Map.

One down side of this approach is that you lose the ability for tools to validate/auto-complete bean method calls when writing the JSP (or template, or however else you wish to generate the HTML). The up sides include a much more flexible process with fewer classes to modify when you add/change data.


Read about me at frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
Joel Hutters
Greenhorn

Joined: Sep 07, 2006
Posts: 21
Not really sure if I'm doing it right.

Interesting answers both of you. Going to try to explain how my application looks and maybe you it will be easier for me to understand if you use that as reference?

This is the interface for my BlogEntryDAO...


This is a DTO, or is it not?


Then I implemented my POJO (this is my business object?) that looks something like this...



Hmm, but then you say that my business service doesn't need to use any DTO:s, and that my command object may return my business object to the JSP-page? Do you mean my BlogEntryService object, or another what do you mean by business object. Hmm, I don't know how to get this right...
[ November 01, 2006: Message edited by: Joel Hutters ]
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
Hmm. I can see that you are confused.

My take on this would be to separate the responsibilities as cleanly as I can. I'd probably split this into just two classes: a "DAO"-style class which deals with the database stuff, and a BlogEntry domain class (also known as a POJO, because it does not implement or use any "framework" classes, just ordinary Java.

So, using my own Stringtree database layer, the two classes might look something like





To use these, I'd probably write three simple servlets: one which accepts parameters and creates/updates a BlogEntry, and one which looks up one entries, and one which looks up a list of entries. The lookup servlets would place the resulting BlogEntry or List into the context for use by a JSP or template. Here's an example:




Sorry that these examples turned out so large, but but they are complete - no extra DTO or other classes needed.

Does that make any sense?
Joel Hutters
Greenhorn

Joined: Sep 07, 2006
Posts: 21
Frank, you don't need to apologize for the long code example, I guess it's something like that I need

However, when looking at your code examples, it feels like your way of implementing it, is very similar to how I did it before making this thread. Instead of using servlets, I have my front controller which invoke my commands which can be seen as a variant of your "simple" servlets. I guess I will go back to this way of implementing it hmm.

Which layer does the servlets/command belongs to? UI controller? How do you avoid to put to much logic in the servlets/command classes? What I mean is that these are often specific for the view of a web page.

Would you mind showing a how a typical Pojo/domain class looks like or is it as simple as the BlogEntry class? Looks like typical Java Bean to me.

Another question. I use an external API, called IPX for sending SMS-messages from my Blog. There are several lines of code required to be able to send a message, isn't it bad to put this in a command class?

Thank you for still having the energy to answer my posts.
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
when looking at your code examples, it feels like your way of implementing it, is very similar to how I did it before making this thread.

This is probably true. The way I tend to approach software development is to do "just enough and no more". The example of the CRUD operations on a blog did not need any more than two classes plus a few very "thin" servlets, so that's all I wrote.

Instead of using servlets, I have my front controller which invoke my commands which can be seen as a variant of your "simple" servlets.

Can you tell us a bit more about what code is in this "front controller"? One of the main reasons I wrote a very simple servlet (which does nothing except extract arguments into an object and call a domain method) is that there is as little as possible in the servlet which neads testing. I like virtually all my code to be testable without the trouble and delay of packaging and deploying to a server, accessing remote URLs, etc. So I put everything in the layer "below" the servlets. In this case that is the BlogEntry and the DAO (so far).

Which layer does the servlets/command belongs to? UI controller? How do you avoid to put to much logic in the servlets/command classes? What I mean is that these are often specific for the view of a web page.

I would still keep such behaviour out of the servlet/JSP/template layer. If you have more complex behaviour, just construct (or fetch from the servlet context it you want it to hang around) a domain object which does what you need. The code in the servlet should still be at most just: extract parameters + servlet settings, construct or initialise one or more objects, pass to a domain method.

If at all possible, make it even simpler, such as: retrieve an object from the servlet context, and call a method passing in the extracted parameters without creating a new object. The key is keep the servlet/JSP layer completely free of any decision making or business knowledge.

Would you mind showing a how a typical Pojo/domain class looks like or is it as simple as the BlogEntry class? Looks like typical Java Bean to me.

This one looks like a Java bean because the scenario I "answered" had hardly any behaviour. Personally I would usually prefer classes with more behaviour than data.

I use an external API, called IPX for sending SMS-messages from my Blog. There are several lines of code required to be able to send a message, isn't it bad to put this in a command class?

I'd start by creating a method which reduces that "several lines of code" to one method call with the appropriate parameters (maybe something like sendSMS(String destinationNumber, String message) and testing that on its own without any servlets, application classes, DAOs or anything else.

Then I'd look at where to put that method. This decision would depend to some degree on how complex the one-time setup process is for the SMS send. If the setup is "expensive", then I would consider placing it in its own class with the setup done in the constructor. That way the application can create a single SMS sender at startup and reuse it wherever needed. If there is no particular setup beyond that which is done for each message, then you might as well put the sendSMS method in the class which uses it.

As for the introduction of command objects, I've not seen anyting in the examples which would seem to need them yet. If I did, the servlet might look more like: extract a dispatcher object from servlet context, extract request parameters and pass them in to a dispatch method on the dispatcher object (as a custom object, a Map, or as raw String parameters). Any decisions, parameter processing, or creation of command objects would take place inside the dispatcher object. The dispatcher object is just regular Java (A POJO, if you prefer). That way the dispatcher object can be called equally well from your test code, from a servlet or even from other things such as a web service handler or JMS listener.

Following the example, if (rather than the simple approach in my post above of one servlet per action) we wanted a single servlet which decides what to do based on an "action" parameter it might look something more like:



The dispatcher dispatches requests to a command handler, each handler implemets a very simple interface such as:



And the dispatcher might look like:



Note that this is not really the Command Object pattern, as there is only one object of each handler class, shared by all requests of the same type. It's not much more difficult to create a new object each time, but (as I pointed out above) there's no obvious need yet.

You should also notice that the code is growing bigger. This is a particular worry as it has grown bigger for no increase in functionality. That's why I deliberately went for a very simple approach originally. Be ruthless about simplicity. If you don't need it right now, don't code it.

On the up side, look at the dependencies between classes, though. The Servlet class(es) are the only classes in the system which know or care about anything from the Servlet API. The DAO class(es) are the only classes in the system which know or care about how or where the data is stored. Everything is just Java and can be tested and reused independently.

You can tell this separation works, because I was able to completely redesign the Servlet/HTTP layer without a single change to the BlogEntry or DAO classes. They still do their jobs just as in the original design.

Thank you for still having the energy to answer my posts.

You're welcome. Any more questions?

darned HTML processing ate all my < and >
[ November 02, 2006: Message edited by: Frank Carver ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Front controller and DAO, design question!
 
Similar Threads
Retrieving and updating Composite Transfer Objects
Use of DAO as a Command?
Using Servlet as a Dispatcher
page relaod probem- resending data to servlet
Struts selection