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.
Joined: Jan 07, 1999
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.