In my web application i want to have certain necessary things in all of the "pages" of it, such as connection to the database, user information, template processing, etc. Until recently i would have an abstract servlet that would init all of the above in its doGet or doPost method, define the abstract method doLocalLogic(HttpServletRequest req, HttpServletResponse res) and would call it from the doGet/doPost method. All the extending classes would enjoy the database connection, user info, etc. Unfortunately, it turned out to be bad practice.
What I am thinking now is to create an abstract class that does all that, all the logic from my servlets would be moved to the children of this class, and the servlets would just create instances of those children.
However, that leads to creating one more class per every page in my app. Moreover, when you create a new servlet, you don't have any clues in the form of abstract methods you need to override, as you would having an abstract servlet.
Is there a better way of doing it?
First of all I would argue that your approach with doLocalLogic() is not bad as long as you are passing this local logic through parameters, not through fields (threads are shared between requests/threads):
public void doLocalLogic(
Connection connection,
UserInformation user,
//...
HttpServletRequest req,
HttpServletResponse res
)
The only problem is that you do prepare a lot of data even if you don't need them in the servlet. And it's not scalable.
What you really need is a more robust... framework. First you probably need a web framework to avoid coding to servlet API directly. Secondly you need IoC like Spring to manage your dependencies. Instead of eagerly creating them and passing over, each service just asks for required dependencies.
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