问题
What's the best way to store a variable that can be used throughout a .JSP website? I have a keycode that is a bunch of numbers keycode = XXXXXXXXXXXXXXXXXXXXX and I want to be able to access that code in various pages while having the keycode live in one location.
The variable doesn't change often but I'd like to be able to just swap it out in one place and not everywhere it's referenced.
回答1:
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?
来源:https://stackoverflow.com/questions/22049414/store-variable-for-jsp-usage