anthonyms
anthonyms

Reputation: 948

Java Servlet extend another Servlet

The init method in most (all) of my servlets is similar. Mostly initializing a DataSource

I am thinking of creating a BaseServlet having a protected DataSource and the init method implemented and all other servlets extend this BaseServlet.

Any Gotchas I should be wary of?

Upvotes: 1

Views: 1650

Answers (2)

Santosh
Santosh

Reputation: 17923

In the current approach:

  1. Every Servlet extending BaseServlet will create its own datasource as the init() method will be called multiple times.
  2. I assume this is not what you want to accomplish and you are looking for a single datasource to be used across all the Servlets.

Assuming above is true, I would suggest following

  1. Wrap your datasource in a singleton class. This will make sure that datasource initialized only once. Use eager initialization to make sure the Datasource is initalized at the class load itself
  2. Use this class to get the datasource/connections in your servlet class.

Upvotes: 1

Jacky
Jacky

Reputation: 1905

If you just need initialize the Database related stuff, you can put that into ServletContext, I am not a fun of so many class inheritance.

nowadays, seems we don't just start from servlet, why not choose a framework?

Upvotes: 1

Related Questions