Share on Google+Share on Google+

Java ServletContext Interface

In this tutorial, we will discuss about ServletContext Interface.

Java ServletContext Interface

In this tutorial, we will discuss about ServletContext Interface.

ServletContext Interface :

ServletContext defines set of methods that helps servlet to communicate with its servlet container. ServletContext object is used to communicate with the servlet container. There is only one ServletContext object per web application. It is initialized when your web application is started and destroyed when your application is being shutdown.

It provides many methods. We are defining some of them -

  • getAttribute(String name) : it returns attribute of servlet container of specified name. If specified name not present then return null.
  • getContext(String uripath) :  It returns a servletContext object corresponding to the given URL on the server.
  • getMimeType(String file) : It returns the MIME type of the given file.If MIME type is unknown then return null.
  • getServletContextName() : this method returns name of the web application belonging to the given ServletContext as defined in web.xml.

Other methods are - getAttributeNames(),getInitParameter(String name), getInitParameterNames(), getMajorVersion(), getMinorVersion(), getNamedDispatcher(String name), getRealPath(String path),getRequestDispatcher(String path), getResource(String path), getResourceAsStream(String path), getResourcePaths(String path), getServerInfo(), getServlet(String name), getServletContextName(), getServletNames(), getServlets(),
log(Exception exception, String msg), log(String msg), log(String message, Throwable throwable), removeAttribute(String name),
setAttribute(String name, Object object).

Example : -

import javax.servlet.*;
import javax.servlet.http.*;
public class ServletContextExample extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
PrintWriter pw = response.getWriter();
ServletContext context = getServletContext();
pw.println("Email: " + context.getInitParameter("email"));

web.xml -

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" xmlns="" xmlns:web="" xsi:schemaLocation="" id="WebApp_ID" version="2.5">

<param-value>[email protected]</param-value>


Output :


Posted on: October 5, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.