在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
。电子邮件&#39;测试&#39;值不打印。为什么?如何获得上下文参数?
答案 0 :(得分: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>
希望这有帮助。