Is it better to have lots of methods to my servlet, or to keep the code inside the doGet or doPost method?

Ryan Breidenbach

There are probably two questions here: Can you put all your code in the doXXX method(s) and Should you put all you code in the doXXX method(s).

As for the first part - yes, you can put all the code in your servlets. However, you need to be aware of a couple of things. First, this obviously limits your servlet to a specific task. This is fine if this is what you are wanting. Also, know that servlets are not thread-safe unless it explicity implements SingleThreadModel, so you don't want any unsychronized access to a class-scoped attribute. In fact, you are probably best not using any "non-constant" class-scoped attribute. You are safer creating attributes at the method level and passing them as parameters. As for your question of how you return a ResultSet from a public void doXXX method - you can't. Instead, you would probably place this object in the request/session as so:

ResultSet rs = loadData();
req.getSession().setAttribute("resultSet", rs);
Now the object can be retrieved from the request/session by another servlet of JSP.

Now, for the second part - should you do all the work in the servlet class. Well, this depends. If you application is fairly simple, you can get away with this because you won't have that much code to maintain. However, once your application becomes somewhat complex, you probably want to employ the Front Controller Pattern. Basically, this is a single servlet that intercepts all application requests and forwards them to other classes to be processed. This pattern has several advantages:

  • Your application is very extensible. To add another piece of functionality, you simply create a class to encapsulates this fucntionality - your servlet code remains unchanged.
  • Single point of entry to your site. Since all requests go throught the same servlet, you have one place for error-handling, logging, etc.
  • Decouples application code from web interface. Since classes independant of your servlet our handling the processing, they can be reused by other non-web components.
For more on this pattern and other J2EE patterns, go to Sun's J2EE Patterns Catalog.

Hope this helps.

[Make sure to also read the forum thread where this question was posed for more advice. -Alex]

Comment and Contribute






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



We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.