Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Shared Object, Synchronization, Servlet Context

 
Vikas Aggarwal
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have 2 problems:
First One:
I have a servlet which reads a property file and sets all of the properties (name-value pairs in a hashtable) from that files to the servletcontext so that for other servlets there is no need to read the prop file again and again. Any servlets can take the hashtable object from servletcontext and read it. Now is it necessary to synchronize the Hashtable object before storing that to servletcontext. Please note that the hastable is only for the "Read-Only" access.
Second One:
It is related to the first one only. In one of the servlets I used following:
ServletContext ctx=getServletContext();
Hashtable myhash=null;
myhash=(Hashtable)ctx.getAttribute("prophash");
private String mypath=myhash.get("myproppath");
Can I make either of the Hashtable "myhash" or String "mypath" static so that I don't have to fetch the Hashtable or String again and again even from the servlet context.
I am not sure about it. Please correct me wherever I am wrong.
Thanks a lot.
 
Ken Robinson
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are a few things you can do with the first problem. What I would suggest is to utilize the <context-param> element in the web.xml file.

In the above, you can of course assign the Key and Value Strings to whatever you like. The description is optional, but makes reading the web.xml a bit easier.
What happens is that the server automatically loads these parameters for you and makes them available in the ServletContext for you. Since you are loading a Properties file, this provides the same exact functionality. Simple use the ServletContext.getInitParameter(String key) method. This method takes the value in the <param-name>element as it's arguement and returns the value in the <param-value> element.
Using this method, you have a very easy and standard way for all components of your web app to get to these parameters without having to worry about any sychronization issues.
The second problem can be solved in a number of ways. If you are using Servlets all throughout your app, just get a handle to the ServletContext in the init method. Keep it as a member var so that you will not have to get the ServletContext for each call. Depending on how often you need this, you could also just get the getServletContext() method, which is part of the javax.servlet.GenericServlet class, inherited by every servlet created.

Hope this helps.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic