This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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.
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.