How Do I Create A Global Jsp Variable That I Can Access Across Multiple Pages Or Inside Frames/iframes?
Solution 1:
As I've already commented, you can use ServletContext to maintain the variables for all your application. Do not confuse this with static variables, because the ServletContext will die when your application is undeployed but static variables will be alive until the JVM is turned off.
You can save variables in ServletContext by using setAttribute
method. Also, you can get the actual value by using getAttribute
. Let's see a sample of ServletContext in a servlet:
publicclassSomeServletextendsHttpServlet {
publicvoiddoGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
ServletContextservletContext= getServletContext();
StringsomeAttribute= servletContext.getAttribute("someAttribute");
System.out.println("someAttribute value: " + someAttribute);
}
}
Also, you can use a Listener to ServletContext, so you can execute some code when the application starts (is deployed correctly) to initialize the attributes on the ServletContext) and when it finish (before its undeployed).
public final classMyAppListenerimplementsServletContextListener {
publicvoidcontextInitialized(ServletContextEvent event) {
System.out.println("Application gets started.");
ServletContext servletContext = event..getServletContext();
servletContext.setAttribute("someAttribute", "Hello world!");
}
publicvoidcontextDestroyed(ServletContextEvent event) {
System.out.println("Application has finished.");
}
}
If you're using Java EE 5, you should configure the listener in the web.xml
<listener><listener-class>mypackage.listener.MyAppListener</listener-class></listener>
Post a Comment for "How Do I Create A Global Jsp Variable That I Can Access Across Multiple Pages Or Inside Frames/iframes?"