2017-06-13 75 views
0

web.xml我有如何用jstl打印context-param?

<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。電子郵件的「測試」值不會打印。爲什麼?如何獲取上下文參數?

回答

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> 

希望這會有所幫助。