Java 从 JSP 页面上的 ServletContext 获取属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25621497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:48:32  来源:igfitidea点击:

Get attribute from ServletContext on JSP page

javajspspring-mvcel

提问by Turlife_07

How can I find my attribute from ServletContext object on JSP page?

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

I set it before in:

我之前设置的:

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) {

}}

and now want to get on JSP page. Maybe it possible to do with ${pageContext.servletContext.attributeNames}?

现在想进入JSP页面。也许可以用${pageContext.servletContext.attributeNames}

采纳答案by Nirav Prajapati

using jstl you can directly get application object in jsp

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

${applicationScope['attributeNames']}

by using this expression you can get your application level object directly in jsp

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

OR

或者

using scriptlet also can get application object in jsp and if you are running on web_app version 3.0 and has Servlet 3.0 API you can directly get ServletContext object form HttpServletRequest as shown in below example:

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

<%

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

%>

but you have to cast your application object when you use scriptlet to get application object so JSTLis much better to use then scriptlet code

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

Read more:

阅读更多: