How to access environment variables from JSP page

2019-01-19 07:03发布

问题:

How can I access environment variables from a JSP page? Does one of the implicit objects give access to them? I couldn't find an example addressing this specific issue. Ideally I'm looking for something like:

<c:set var="where" value="${myEnvironment.machineName}">

回答1:

You can read the properties file at the server start-up using ServletContextListener and store it as application scoped attribute to access it from anywhere in the application.

Steps to follow:

.properties:

machineName=xyz

web.xml:

<listener>
    <listener-class>com.x.y.z.AppServletContextListener</listener-class>
</listener>

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

JSP:

Then you can just treat it as Map in EL.

${myEnvironment['machineName']}

or

${myEnvironment.machineName}

Read more about JSTL Core c:set Tag

The <c:set> tag is JSTL-friendly version of the setProperty action. The tag is helpful because it evaluates an expression and uses the results to set a value of a JavaBean or a java.util.Map object.

The <c:set> tag has following attributes:

If target is specified, property must also be specified.

Read more about it HERE


If you are looking for sample code then find it here. Please find it at below posts. It might help you.

  • Acces value between two jsp with jstl

  • JSP - Standard Tag Library (JSTL) Tutorial


More samples on other scopes.

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

In your case you have set an attribute where in default page scope.



标签: java jsp jstl el