Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get attribute from ServletContext on JSP page

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

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}?

like image 461
Turlife_07 Avatar asked Sep 02 '14 10:09

Turlife_07


1 Answers

using jstl you can directly get application object in jsp

${applicationScope['attributeNames']}

by using this expression you can get your application level object directly in 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:

<%

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

%>

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

Read more:

like image 52
Nirav Prajapati Avatar answered Oct 29 '22 16:10

Nirav Prajapati