【问题标题】:How to print context-param with jstl?如何使用 jstl 打印上下文参数?
【发布时间】:2017-06-13 00:35:19
【问题描述】:

web.xml我有

   <context-param>
      <param-name>email</param-name>
      <param-value>test</param-value>
     </context-param>

在jsp中我有

 <c:out value= "MUST PRINT EMAIL">  
    </c:out> 
    <c:out value= "${applicationScope.email}">  
    </c:out>  

但这仅打印 MUST PRINT EMAIL 。不打印电子邮件“测试”值。为什么?如何获取上下文参数?

【问题讨论】:

    标签: java tomcat web.xml


    【解决方案1】:

    我认为你不能直接这样做,你可以通过这段代码转储应用程序范围内的所有属性

    ${pageScope}<br> ${requestScope}<br> ${sessionScope} <br> ${applicationScope}
    

    或更详细

    <%
        Enumeration attrNames=request.getServletContext().getAttributeNames();
        while(attrNames.hasMoreElements()){
            String ctxAttribute=(String) attrNames.nextElement();
            out.print("<br> Attribute Name --> "+ctxAttribute+", has value Value --> "+request.getServletContext().getAttribute(ctxAttribute));
        }
    
    out.println("<br><br>");
    
        attrNames=application.getAttributeNames();
        while(attrNames.hasMoreElements()){
            String ctxAttribute=(String) attrNames.nextElement();
            out.println("<BR> Attribute Name --> "+ctxAttribute+", has value Value --> "+application.getAttribute(ctxAttribute));
        }
    %>
    

    如果你想通过这种方式获取这个参数,你可以在初始化上下文的时候把这个属性放到应用范围内:

    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    
    public class MyContextListener implements ServletContextListener {
        private static final Log logger = LogFactory.getLog(MyContextListener.class);
    
    
        @Override
        public void contextInitialized(ServletContextEvent servletContextEvent) {
            String email= servletContextEvent.getServletContext().getInitParameter("email");
            logger.info("Use email:" + email);
            servletContextEvent.getServletContext().setAttribute("email", email+"==setbylistener");
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent servletContextEvent) {
    
        }
    }
    

    别忘了在你的web.xml中配置它

      <context-param>
          <param-name>email</param-name>
          <param-value>test123</param-value>
      </context-param>
    
      <listener>
            <listener-class>MyContextListener</listener-class>
      </listener>
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多