What is ServletContext?
Servlet Context is basically a configuration object that is used by servlet container to initialize various parameters for a web application
Alll servlets can access the context object. For example, let us assume that there are 10
servlets are there in u r web application, if you want to share same data to all servlets then
we can share that data using servlet context, because every servlet can have interaction with that application environment.
Usage of ServletContext Interface
Some of the usages of ServletContext object are as follows:
- The object of ServletContext provides an interface between the container and servlet.
- The ServletContext object can be used to get configuration information from the web.xml file.
- The ServletContext object can be used to set, get or remove attribute from the web.xml file.
- The ServletContext object can be used to provide inter-application communication.
Advantage of ServletContext
Easy to maintain
If any information has to be shared to all the servlets then We provide this information in the web.xml file, so if the information is changed, we don't need to modify the servlet. Thus it removes maintenance problem.
Example demonstrating usage of ServletContext
web.xml
<web-app ...>
<context-param>
<param-name>driverName</param-name>
<param-value>sun.jdbc.JdbcOdbcDriver</param-value>
</context-param>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
MyServlet class :
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ServletContext sc = getServletContext();
out.println(sc.getInitParameter("driverName"));
}
}