I am building an application which, among other things, loads a XML file which is the same for all the users.
If i load this file from the init() method, then if 1000 users open a session, the file will be loaded 1000 times, isn’t it ?
How to load the file one time rather than 1000 times ???
For instance using a ServletContextListener: take a look
at this example . You can then store the file in a static variable, but remember to handle concurrent access.
BUT, when i try to get the attribute from the context inside the init() method,
i get a Null Pointer in this example :
Do you know what to do ?
2 / Another question : from my point of view, a listener is supposed to listen to events like clicking on a button, i do nnot understand why we use a listener for a context ??:mellow:
[size=2]
package com.example.test2vaadin;
public class Test2vaadinApplication extends Application [b]
implements ServletContextListener
[/b]{
ServletContext context;
@Override
public void init() {
Window main = new Window("Hello window"); //window means browser or tab
setMainWindow(main);
main.addComponent(new Label("Value of TEST attribute coming from the context : "
+[color=#da1616]
context.getAttribute("TEST")
[/color])); [color=#bb1839]
=> Null Pointer Exception
[/color]
}
public void [b]
contextInitialized
[/b](ServletContextEvent contextEvent) {
System.out.println("------------------- Context Created ------------------");
context = contextEvent.getServletContext();
// set variable to servlet context
[color=#1baf16]
context.setAttribute("TEST", "TEST_VALUE");
[/color]
}
public void contextDestroyed(ServletContextEvent contextEvent) {
context = contextEvent.getServletContext();
System.out.println("------------------- Context Destroyed ------------------");
}
}
[/size]
Well, this particular one listens to when servlets are started and stopped. Same concept, different scale. The ServletContextListener is part of the Java Servlet standard, not just a Vaadin thing.
1 / Your solution works fine, in my case, i get the attribute this way :
[size=2]
main.addComponent(new Label("Value of TEST attribute coming from the context : "
+((WebApplicationContext)getContext()).getHttpSession().getServletContext().getAttribute("TEST")));
[/size]