I am working on a Tomcat application which populates a HashMap on startup. I set it in the ServletContext using ServletContext.setAttribute. However, I have some non Java EE classes also in this application (basically my webservice calls call those methods). I want to access this HashMap in those Methods. What is the best way to do it?
-
Either send them the hashMap and let them do whatever you want to do, or even better: expose a service that handles the map. – Nir Alfasi Jul 15 '14 at 23:40
-
Is there a way I can do it without setting it in the Context? Is there a way I can keep a handle to an Object through out the lifetime of my Tomcat application? – Anuja Khemka Jul 15 '14 at 23:53
-
yes, that's what I said: create a service (could be a singleton) that handles that map. You can access the service from anywhere and that service will "hide" the hashmap and expose only its functionalities. – Nir Alfasi Jul 16 '14 at 00:45
4 Answers
Fetch the HashMap in your web service class and pass on the same as method argument to your non Java EE classes.

- 67,789
- 12
- 98
- 136
-
Is there a way I can do it without setting it in the Context? Is there a way I can keep a handle to an Object through out the lifetime of my Tomcat application? – Anuja Khemka Jul 15 '14 at 23:53
-
ServletContext is used for saving things that you want to use across different application. ServletConfig is used to store things that you want to access only in a particular application. – Juned Ahsan Jul 16 '14 at 00:00
-
-
I want to use ServletContext but was unable to retrieve ServletContext as it is a non Tomcat Class. However now I am using ServletContextAware to retrieve it. – Anuja Khemka Jul 18 '14 at 00:17
Your web service should have access to HTTP Request and Response where you can get ServletContext. When web services call these non J2EE methods, you can pass the map as a argument parameter.

- 9,982
- 61
- 44
-
I wish I could but the code is managed by spring and generated by CXF and didnot want to disturb that. – Anuja Khemka Jul 18 '14 at 00:18
-
You can add a ServletContextListener in the web xml file. In this listener, you can load your items into a static HashMap where later your POJO will have access to them. – sendon1982 Jul 18 '14 at 03:59
-
You can make your map available to all classes of your application:
Using a Singleton
See What is an efficient way to implement a singleton pattern in Java?
Using Tomcat global JNDI tree (not recommended, but you can do it).
See How do you save name-value pairs in Tomcat environment? and Apache Tomcat 7 - JNDI Resources HOW-TO

- 1
- 1

- 41,222
- 15
- 102
- 148
Thank you all for the suggestions. However what I was trying to achieve was achieved by the following example:
http://www.xinotes.net/notes/note/1772/
It gave me a method to retrieve the context in non-Tomcat handled classes.

- 265
- 1
- 6
- 17