Reputation: 13315
how can i load data into memory with a tomcat server ?
i have a java class that load data from a file. i want to load the data into memory once and that every time the client request a page that uses that class the data will be used from the memory.
for example
class MyClass
{
HashMap data = new HashMap(100);
public void LoadDataFromFile()
{.....}
public void UseTheData(String input)
{....}
public MyClass(){ LoadDataFromFile();} // c'tor load data
public SetInput(String Input)
{
UseTheData(input);
}
}
and in my jsp file
Myclass myclass= new MyCass();
myclass.LoadDataFromFile();
myclass.UseTheData();
i know i should use JSTL in the jsp file
if i use the scope="session" will the data loading will remain ?
<jsp:useBean id="myclass" class="MyClass" scope="session">
<jsp:setProperty name="myclass" property="input" value="blabla" />
</jsp:useBean>
if i do the data loading in the constructor, can i make sure the class is init only once ?
Upvotes: 2
Views: 984
Reputation: 691943
Create a ServletContextListener
and register it in your web.xml file. In the ServletContextListener
, when the application is initialized, read the file and store it in an attribute of the ServletContext
. This attribute is then easily accessible from your Java and JSP code.
Upvotes: 3