是否为.JSP使用存储变量? [英] Store Variable For .JSP Usage?

查看:48
本文介绍了是否为.JSP使用存储变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

存储可在整个.JSP网站中使用的变量的最佳方法是什么?我有一个键码,它是一堆数字,键码= XXXXXXXXXXXXXXXXXXXXX,我希望能够将多个键码放在一个位置同时访问各个页面中的代码.

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.

推荐答案

要将变量存储在应用程序范围内,应将其另存为ServletContext .rel ="nofollow noreferrer"> ServletContextListener :

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");
    }
}

然后,您可以通过表达语言从您的JSP访问此值:

Then, you can access to this value from your JSP through Expression Language:

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

和/或在处理请求时在您的servlet中.例如,在 doGet :

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"
}

有关Java Web应用程序开发中变量范围的更多信息:如何通过c:set将参数传递给jsp:include?JSP中变量​​的作用域是什么?

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?

这篇关于是否为.JSP使用存储变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆