To store a variable in application scope, you should save it as an attribute in ServletContext
. You can access to the ServletContext
when the application is deployed, by using ServletContextListener
:
public class AppServletContextListener implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent arg0) {
//use this method for tasks before application undeploy
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
//use this method for tasks before application deploy
arg0.getServletContext().setAttribute("keyCode", "foo");
}
}
Then, you can access to this value from your JSP through Expression Language:
${keyCode} //prints "foo"
${applicationScope.keyCode} //also prints "foo"
And/or in your servlet when processing the request. For example, in the doGet
:
public void doGet(HttpServletRequest request, HttpServletResponse response) {
ServletContext servletContext = request.getServletContext();
System.out.println(servletContext.getAttribute("keyCode")); // prints "foo"
}
More info about the scope of the variables in Java web application development: How to pass parameter to jsp:include via c:set? What are the scopes of the variables in JSP?