how to create singleton classes for multiple uses and how to connect to jsp with that singleton class
I'm not sure why yould want to connect to a singleton from you JSP directly. If you want to access utility function I'd go with a JSTL function:
<function>
<name>decodeBase64</name>
<function-class>nl.wikiwijs.web.portal.Base64Util</function-class>
<function-signature>java.lang.String stringDecodeBase64(java.lang.String)</function-signature>
</function>
Where 'function-signature' points to a static method in the 'function-class' class. The above should be in a TLD, after which I can be used like this:
${mynamespace:decodeBase64("my value")}
If the singleton is going to be used to retrieve data or expose business logic I'd move it back into a controller/action/component depending on your architecture.
If you plan to use the Singleton pattern within a JEE application, have a look at this article. It will provide some important insights as well as links for further research.
As stated by p3t0r, using services directly from within your JSP is not architecturally sound. Try seperating concerns by using some kind of MVC framework (e.g. Spring Web MVC, which, in conjunction with the Spring DI container, frees you from using your own singleton implementations, too).
Basic singleton design pattern has few special characteristics:
- No constructor: make sure that the default constructor is private
- Create a static function that calls the private constructor(s) if the object is not instantiated already
- Have a static instance variable that is the type of its own class.
One example of a simple singleton class implementation is:
public class SingletonClass {
private static SingletonInstance si;
private SingletonClass() {
}
public static synchronized SingletonClass getSingletonInstace() {
if (si == null)
return new SingletonClass();
return si;
}
}
for connecting to jsp, you would use p3t0r's answer.
for singleton, you would use a lazy private static class singleton which guarentees thread safety*:
public class SingletonClass {
private static class LazySingletonInitializer {
static SingletonClass instance = new SingletonClass();
}
private SingletonClass(){}
public SingletonClass getInstance() {
return LazySingletonInitializer.instance;
}
}
(*) because static members of a class are guarenteed by the jvm to be initialized by only one thread.