I'm new to web development and am just wondering about best practices for java servlets. Should each servlet perform exactly one action, ie a servlet for login, a servlet for registration etc, or should I look to combine similar actions by passing a different parameter to tell the servlet which action to perform?
Cheers
You should never pass arguments to tell a servlet to do different actions. All you are doing with that is combining 2 servlets into one, and that becomes more difficult to manage. You will want a servlet for each 'action'.
One example of what to avoid is this:
/App/Servlet1?action=edit
if (request.getParamater("action").equals("edit")) {
//update fields
} else if (request.getParamater("action").equals("view")) {
//just query
}
This tends to cause a lot of problems further when you want to redesign anything. You will want to have separate servlets because it is decoupling your logic so that you can easily change it as opposed to coupling its various intricacies of code it shouldn't be related to. Also, look into Separation of Concerns.
Revised/edit: I am going to say this now (much later to the original answer)... You can keep the "multiple actions" concept and put that into a single servlet (controller). That controller could and should delegate to individual action handlers. I think that is the same in terms of separation of concerns AND is cleaner than my original answer. In other words, don't implement anything in the servlet, use that for routing only.
In Frameworks such as Struts there is one single servlet (although there could be multiple instances of it running). This servlet will handle requests for various URLs and pass them off the the relevant action handlers.
I only end up writing extra servlets for serving different content types such as an image rendering servlet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With