Two Laptop Bag
The moose likes Servlets and the fly likes Design Issue: One Servlet Or Many Servlets Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Design Issue: One Servlet Or Many Servlets" Watch "Design Issue: One Servlet Or Many Servlets" New topic

Design Issue: One Servlet Or Many Servlets

Joshua Lam

Joined: Apr 12, 2000
Posts: 14
This is a design question.
In general, is it better to have many servlets each specializing in one function or have one big servlet that multiplexes to many different function?
I do know that in general the servlet itself should not contain the business logic for the function but delegates to other classes.
If we use the one servlet approach, seems like we have to write a big if-elseif statement to determine which business logic class gets what. Would this be difficult to maintain? So if we have more logic to add, we would have to rewrite the servlet code.
Frank Carver

Joined: Jan 07, 1999
Posts: 6920
This is one of the recurring questions in the Servlet world. I'm afraid there is no clear-cut answer. Bear in mind, though that it's not just a choice between lots-o-servlets or big-if-else; there are other options.
The main problem with the lots-o-servlets approach is the management of them. If you're not extremely careful you end up having to hard-code the name of each servlet in many places:- the web server configuration and in all the other servlets and static HTML files which use it. This can make changing the name or responsibilities of a servlet very error-prone.
The main problem with the big-if-else approach is that it forces almost all changes to the calling pattern or the business logic interface to also affect the servlet class. This can cause real problems in a multi-person developer team as everyone needs to edit one file.
One way to break this deadlock is to adopt a dynamically-loaded module approach, where your central servlet acts as a mapping between action-names and action-handlers. The mapping can either come from servlet init parameters, some sort of config file, or (my favourite) from scanning a directory of class files.
This approach decouples the name/action association into several sub-servlets and allows much easier maintenance and parallel development.
The bottom line though, is that in my experience you have to decide on a case-by-case basis which approach is worthwhile.

Read about me at ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
paul wheaton

Joined: Dec 14, 1998
Posts: 20972

I go with the many servlet approach.

permaculture Wood Burning Stoves 2.0 - 4-DVD set
I agree. Here's the link:
subject: Design Issue: One Servlet Or Many Servlets
It's not a secret anymore!