Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many actions should a servlet perform?

Tags:

java

servlets

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

like image 771
Simonw Avatar asked Aug 27 '09 12:08

Simonw


2 Answers

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.

like image 103
Zombies Avatar answered Sep 20 '22 04:09

Zombies


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.

like image 37
pjp Avatar answered Sep 20 '22 04:09

pjp