Originally posted by Bahadar Khan: In j2eeCertificate.com, I have seen this question and among those they have mentioned one of the correct answer as this:
req.getSession().getServletContext();
However I couldn't find anywhere getting ServletContext out of Session!
Please let me know if this is possible?
Hi Bahadar !
This is absolutely valid way to obtain reference to ServletContext. Take a look at HttpSession JavaDoc :
getServletContext
public ServletContext getServletContext()
Returns the ServletContext to which this session belongs.
Returns: The ServletContext object for the web application Since: 2.3
There is no HttpSession.getServletContext() method.
Here are the ways I know of to get a ServletContext:
1) ServletConfig.getServletContext() 2) GenericServlet implements ServletConfig, so HttpServlets all have a getServletContext() method 3) In a Filter you have access to the FilterConfig which is set in the init(FilterConfig fc) callback. You can use FilterConfig.getServletContext(). 4) In a ServletContextListener or a ServletContextAttributeListener, the event passed to the listener methods has a getServletContext() method.