I am currently using a ServletContextListener
to set the paths of JSPs in a web application. The paths are stored as context parameters in web.xml
and retrieved by the listener:
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext sc = sce.getServletContext();
sc.setAttribute("urlOfThisPage", sc.getInitParameter("urlOfThisPage"));
sc.setAttribute("urlOfThatPage", sc.getInitParameter("urlOfThatPage"));
In the application servlets, the path of a particular JSP can easily be retrieved from ServletContext
.
My question relates to handling a properties file in the same way. I read a lot about this on other StackOverflow pages like 2161045.
Am I correct in assuming that the properties file should be read by a listener and stored in ServletContext
using a Property
object? but then if this is the case, how would I retrieve a particular property from the properties file?
At the moment I am using this sort of code in my servlets to get the value of an attribute from ServletContext
.
String url = (String) sc.getAttribute("urlOfThisPage"); // Use ServletContext to get JSP's URL.
But I am not sure how to extend this to accessing a properties file.
I have tried the following in the ServletContextListener
:
Properties properties = new Properties();
properties.setProperty("name", "Akechi Jinsai");
sc.setAttribute("properties", properties);
And in a servlet, using code:
ServletContext sc = request.getSession().getServletContext();
Properties properties = (Properties) sc.getAttribute("properties");
System.out.println("Here: " + properties.getProperty("name"));
"Here: Akechi Jinsai" is displayed but is there a better way of getting a single property in a servlet without looking up things in this way?