如何从 JSP 页面访问环境变量

use*_*173 5 java jsp jstl el

如何从 JSP 页面访问环境变量?隐式对象之一是否可以访问它们?我找不到解决此特定问题的示例。理想情况下,我正在寻找类似的东西:

<c:set var="where" value="${myEnvironment.machineName}">
Run Code Online (Sandbox Code Playgroud)

Bra*_*raj 6

您可以在服务器启动时使用ServletContextListener读取属性文件,并将其存储为应用程序范围的属性,以便从应用程序的任何位置访问它。

要遵循的步骤:

。特性:

machineName=xyz
Run Code Online (Sandbox Code Playgroud)

网页.xml:

<listener>
    <listener-class>com.x.y.z.AppServletContextListener</listener-class>
</listener>
Run Code Online (Sandbox Code Playgroud)

AppServletContextListener.java:

public class AppServletContextListener implements ServletContextListener {

    private static Properties properties = new Properties();

    static {
        // load properties file
        try {
            // absolute path on server outside the war 
            // where properties files are stored

            String absolutePath = ..; 
            File file = new File(absolutePath);
            properties.load(new FileInputStream(file));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        servletContextEvent.getServletContext().
                                    setAttribute("myEnvironment", properties);
    }
}
Run Code Online (Sandbox Code Playgroud)

JSP:

然后你可以把它当作 EL 中的 Map 。

${myEnvironment['machineName']}
Run Code Online (Sandbox Code Playgroud)

或者

${myEnvironment.machineName}
Run Code Online (Sandbox Code Playgroud)

阅读有关JSTL 核心标签的更多信息c:set

<c:set>标签是JSTL的友好界面setProperty的操作。该标签很有用,因为它计算表达式并使用结果设置 aJavaBeanjava.util.Map对象的值。

<c:set>标签具有以下属性:

在此处输入图片说明

如果指定了目标,则还必须指定属性。

此处阅读更多相关信息


如果您正在寻找示例代码,请在此处找到它。请在以下帖子中找到它。它可能会帮助你。


有关其他范围的更多示例。

    <%-- Set scoped variables --%>
    <c:set var="para" value="${41+1}" scope="page" />
    <c:set var="para" value="${41+1}" scope="request" />
    <c:set var="para" value="${41+1}" scope="session" />
    <c:set var="para" value="${41+1}" scope="application" />

    <%-- Print the values --%>
    <c:out value="${pageScope.para}" />
    <c:out value="${requestScope.para}" />
    <c:out value="${sessionScope.para}" />
    <c:out value="${applicationScope.para}" />
Run Code Online (Sandbox Code Playgroud)

在您的情况下,您已where在默认page范围内设置了一个属性。