【问题标题】:Get attribute from ServletContext on JSP page从 JSP 页面上的 ServletContext 获取属性
【发布时间】:2014-10-26 14:34:03
【问题描述】:

如何从 JSP 页面上的 ServletContext 对象中找到我的属性?

我之前设置在:

public class MyServletContextListener implements ServletContextListener{

private static final Logger logger = LoggerFactory.getLogger(MyServletContextListener.class);

@Override
public void contextInitialized(ServletContextEvent event) {
    logger.info("Init gameEngine in listener");
    Engine engine = Engine.getInstance();
    event.getServletContext().setAttribute("engine", engine);
}

@Override
public void contextDestroyed(ServletContextEvent event) {

}}

现在想上JSP页面。 也许有可能与${pageContext.servletContext.attributeNames} 有关?

【问题讨论】:

    标签: java jsp spring-mvc el


    【解决方案1】:

    使用jstl可以直接在jsp中获取应用对象

    ${applicationScope['attributeNames']}
    

    通过使用此表达式,您可以直接在 jsp 中获取应用程序级别的对象

    使用scriptlet也可以在jsp中获取应用对象 如果您在 web_app 3.0 版上运行并且具有 Servlet 3.0 API,您可以直接从 HttpServletRequest 获取 ServletContext 对象,如下例所示:

    <%
    
         ServletContext sc = request.getServletContext();
         sc.getAttribute("attributeName");
    
    %>
    

    但是当您使用 scriptlet 获取应用程序对象时,您必须强制转换您的应用程序对象,所以 JSTL 比 scriptlet 代码好用得多

    Read more:

    【讨论】:

    • 感谢您的回答。我使用了 ${applicationScope.engine.rooms},它对我有用!)
    • 没有request.getServletContext()的方法;为什么
    • 改用request.getSession().getServletContext()
    • @shareef 这是因为您在 Servlet API getServletContext() 仅在 Servlet API 3.0 中添加到 HttpServletRequest
    猜你喜欢
    • 2014-10-07
    • 2011-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多