Simply, how do I create a global variable in JSP, such that I can access it across other JSP pages and/or inside frames/iframes? I tried <%!..%> but I got an error that the variable could not be resolved in a separate jsp page. Is it even possible to access JSP variables in more than one page without resorting to query strings, session variables, etcetera?
Thank you.
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
setAttributemethod. Also, you can get the actual value by usinggetAttribute. Let’s see a sample of ServletContext in a servlet: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).
If you’re using Java EE 5, you should configure the listener in the web.xml