2014-02-26 34 views
0

什麼是存儲可以在整個.JSP網站中使用的變量的最佳方式?我有一個keycode,它是一串數字keycode = XXXXXXXXXXXXXXXXXXXXX,我希望能夠在各種頁面中訪問該代碼,同時讓鍵碼在一個位置上。存儲變量對於.JSP的用法?

該變量不會經常更改,但我希望能夠在一個地方將其交換出來,而不是在任何地方引用它。

+2

在應用範圍(所有用戶),中(每用戶)會話範圍,在一個常量(只在部署期間更改)或JNDI值,或... –

+0

它需要太適用於所有用戶,那麼如何執行應用程序範圍路由? – NCoder

+1

http://docs.oracle.com/javaee/6/tutorial/doc/gjbbk.html,http://stackoverflow.com/questions/11091377/using-application-scope-variables-in-java,http:/ /stackoverflow.com/questions/9573021/setting-a-variable-at-application-scope-so-it-shared-among-sessions,依此類推等。 –

回答

1

要在應用程序範圍中存儲變量,應將其保存爲ServletContext中的一個屬性。您可以訪問到ServletContext當應用程序部署,通過使用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"); 
    } 
} 

然後,您可以通過Expression Language訪問從JSP這個值:

${keyCode} //prints "foo" 
${applicationScope.keyCode} //also prints "foo" 

和/或在你的servlet處理請求時。例如,在doGet:關於Java Web應用程序開發的變量的作用域

public void doGet(HttpServletRequest request, HttpServletResponse response) { 
    ServletContext servletContext = request.getServletContext(); 
    System.out.println(servletContext.getAttribute("keyCode")); // prints "foo" 
} 

更多信息:How to pass parameter to jsp:include via c:set? What are the scopes of the variables in JSP?