How to access environment variables on a JSP page

How can I access environment variables from a JSP page? Does one of the implicit objects provide access to them? I could not find an example dedicated to this particular problem. Ideally, I'm looking for something like:

<c:set var="where" value="${myEnvironment.machineName}">
+4
source share
1 answer

You can read the properties file at server startup using ServletContextListener and save it as an application . > to access it from anywhere in the application.

Stages:

.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 consider it as a card in EL.

${myEnvironment['machineName']}

or

${myEnvironment.machineName}

JSTL Core c:set

<c:set> - JSTL- setProperty. , JavaBean java.util.Map.

<c:set> :

enter image description here

, .


, . . . .


.

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

where page.

+4

Source: https://habr.com/ru/post/1540908/


All Articles