Reputation: 13547
In android there is a mechanism of ensuring that only one instance of a class is available to the whole application. This can be done by deriving that class from Application.
Can some thing similar be done in servlets? I want to initialize a class when the application is deployed. This class should have only one instance. So that what all the servlets can access it.
I came to know that you can store your data in the servlet context's hashmap. But I don't want to do that. I want to write my own class with its functions. How should this be done?
Upvotes: 0
Views: 375
Reputation: 421130
I think what you're after is simply a singleton.
This is best implemented by defining an enum with a single instance. (Note that enums allow you to have member functions just as classes.)
public enum YourSingleton {
INSTANCE;
// Your methods...
}
and then you access it as
YourSingleton.INSTANCE
Upvotes: 4
Reputation: 5837
Use singleton pattern
so the first call to instance method (say YourClass.getInstance()
) will create the instance and it will be reused across the application.
Upvotes: 1
Reputation: 66896
So, create whatever class you want with its own functions or whatever you like, and put that in the ServletContext
at startup. You can use a ServletContextListener
to initialize and remove it. What's limiting about that?
Upvotes: 4