Should I use one servlet supporting GET to show pages and POST to process forms, or two separate servlets?

Alex Chaffee

I prefer keeping my servlets as simple as possible. That means one servlet per page, and one per function. In this case, that would mean one servlet to show pages and another servlet to process forms. The trick is, all the servlets can communicate with the common data model, which is stored using session or application attributes.

For example, I have one servlet (actually a JSP) that displays a form. The ACTION for that form is another servlet which processes the parameters. That servlet sends a redirect to the resulting page -- either the original form with an error message, or the "Thanks for filling out the form" page servlet (actually a JSP). This allows me to keep my UI design very flexible. For instance, I can have two different pages call the same "process form" logic servlet, allowing (e.g.) a "Search" box on every page and a separate Search page to use the same behind-the-scenes logic.

(I prefer using browser redirects (sendRedirect()) over RequestDispatcher since it keeps bookmarks and Reload/Refresh logic clean.)

It's definitely a style choice; I like my way because it's more flexible; lumping everything together can lead to brittle spaghetti code.

And as for GET and POST in the same servlet, I think that's kind of messy. I actually like it when POST servlets can still respond to GET requests with the same semantics -- it makes it a lot easier to debug! (I can just type in my test case in the address bar.) Note that this requires that doGet() and doPost() have the same implementation, which is trivial in the Servlet API:

public void doGet(HttpServletRequest req, HttpServletResponse res) {
  doPost(req.res);
}

You should also read the Forum Thread on this subject for many other good comments.

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact