ServletContext is only a single object to a whole Servlet Application. It is once created and initialized by the web container at the container start-up.
A Web application has many Servlet classes and for every servlet there is common object called as ServletContext. So if we have the requirement to have some common service between those servlets then we can be able to provide by initializing ServletContext object with < context-param > tag in the web.xml and hence can be accessed with any of the Servlet instance or ServeletConfig object.
About ServletContext interface
ServletContext is a interface defined in the servlet-api which has many methods defined and can give any required informations about a Servlet Application.
Context object is created by the web container so how we can get this object in our servlet class?
By calling getServletContext() method by our own defined servlet object or ServletConfig object.
1. With ServletConfig Object --> Our Servlet class extends HttpServlet class which internally extends GenericServlet which implements Servlet and ServeletConfig interfaces. And ServletConfig has getServletContext() method.
ServletConfig config = this.getServletConfig();
ServletContext ctx = config.getServletContext();
2. With our own Servlet Object --> This can be achieved by calling getServletContext() method with " this " keyword.
ServletContext ctx = this.getServletContext();
3. With HttpSession object --> This can be done by calling getServletContext() with HttpSession object.
HttpSession session = request.getSession();
ServletContext ctx = session.getServletContext();
How to initialize ServletContext with some values ?
It should be done at the web.xml file under < context-param > tag using < param-name > and < param-value > but should not be under < web-app > because it is common to all the servlet so must be mapped globally.
It should be done at the web.xml file under < context-param > tag using < param-name > and < param-value > but should not be under < web-app > because it is common to all the servlet so must be mapped globally.
<context-param> <param-name> </param-name> <param-value> </param-value> </context-param>
< param-name > contain any logical name.
< param-value > contains value initialized to ServlteContext Object.
0 comments:
Post a Comment