Store Variable For .JSP Usage?

試著忘記壹切 提交于 2021-02-11 15:51:57

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!